我使用以下jQuery从隐藏字段获取文件名,然后将其附加到我的HTML文件名类中。
I'm using the following jQuery to get the filename from my hidden field which I then append to my filename class in my HTML.
filenameCache = $('#example-marketing-material-file-cache').val().replace(/^.*[\\\/]/g, ''); $(".filename").text(filenameCache); <input id="example-marketing-material-file-cache" name="bid[example_marketing_material_cache]" type="hidden" value="1430984214-14326-1254/Banking_Details_Reader.pdf" />但是,我在同一页面上有三个文件附件。我可以重复这个代码三次,改变每个类和ID的名称,但这不是非常干燥。获取每个附件字段的文件名而不重复自己的最佳方式是什么?
However, I have three file attachments on the same page. I could just repeat this code three times changing the class and ID names for each but this is not very DRY. What is the best way of getting the filenames for each attachment field without repeating myself?
推荐答案为文件字段提供一个类似于file_upload的通用类,可以使用 text(fn) 循环遍历文件名字段并更新实例
Give the file fields a common class like of "file_upload" , can use text(fn) to loop over the filename fields and update instances
$files=$('.file_upload'); // loops over all in selector and updates instances $(".filename").text(function(idx , txt){ return $files.eq(idx).val().replace(/^.*[\\\/]/g, ''); });这里假设您有3个,并且它们在页面中有匹配的索引
This assumes that you have 3 of each and they have matching indexing in page
如果只有一个文件名字段
If there is only one filename field
$(".filename").text(function(idx , txt){ return $.map($files, function(el){ return el.value.replace(/^.*[\\\/]/g, ''); }).join(", "); });更多推荐
用jQuery显示多个附件文件名
发布评论