【问题标题】:multiple file inputs, how to get id of each for preview多个文件输入,如何获取每个文件的 id 以进行预览
【发布时间】:2013-01-25 17:50:43
【问题描述】:

在尝试让多文件选择输入与预览一起使用,但后来发现 IE 不支持它,我改变了我如何进行多文件上传。

现在我有多个单个文件输入,每个输入都有自己的“预览”div。每个 select 和 preview div 的 id 链接(输入 select id="file1",preview div id="previews_file1")等最多 10 个。

我正在使用此代码预览所选图像:

function readURL(input) {
if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
        var thisid = $(this).id;
        var container = $('#previews_'+ thisid);
        var image = $('<img>').attr('src', e.target.result).css({'max-width':'200px','max-height':'200px'});
        image.appendTo(container);
    };
    reader.readAsDataURL(input.files[0]);
}
}

带有html:

    <div id="previews_file1" style="float:left;width:200px;height:200px;"></div>
    <input type='file' id="file1" name="file1" onchange="readURL(this);" style="float:left;" />

我的问题是我似乎无法将输入 id 传递给函数,当然 $(this).id 不起作用。我将如何将预览放入正确的预览 div 中?

编辑:

js 小提琴:http://jsfiddle.net/KE3tv/

【问题讨论】:

  • jsfiddle 控制台“未捕获的 ReferenceError:未定义 readURL”

标签: jquery image input upload


【解决方案1】:

http://jsfiddle.net/KE3tv/1/

<input type='file' name="file1" />
<input type='file' name="file2" />
<input type='file' name="file3" />

JQ

$('input[type="file"]').on('change', function(){
    ...
    // name is already a unique attribute, no need for an id
    var container = $('#previews_'+ $(this).attr('name')); 
    ...
});

【讨论】:

  • 这行得通,尽管我不得不因为 IE 而改变我这样做的方式,不过还是谢谢
猜你喜欢
  • 2015-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-14
  • 2016-03-06
  • 2018-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多