用jQuery显示多个附件文件名 [英] Display multiple attachment filenames with jQuery

查看:110
本文介绍了用jQuery显示多个附件文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下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显示多个附件文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆