FileReader API多次调用使用相同ID标签的图像

FileReader API to call images using same ID tag multiple times?

本文关键字:ID 标签 图像 API 调用 FileReader      更新时间:2023-09-26

我一直在努力弄清楚如何才能拥有HTML5 FileReader API在重复的id上多次显示相同的图像。

植入的例子如下:http://jsfiddle.net/2xES5/37/

通过click创建div,并且在每个创建的div中包含一个调用(id="list")来显示图像。然后,当有人添加他们的图像时,每个新创建的div都包含图像。

但是问题是Filereader不能识别同一个div id的多个实例。它只在一个DIV中显示图像,而我希望每个DIV中重复显示图像。

希望有人能把我引向正确的道路。谢谢


基本FileAPI: http://jsfiddle.net/2xES5/35/

if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('Sorry The HTML5 FileReader API is not fully supported in this browser.');
}
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
    // Only process image files.
    if (!f.type.match('image.*')) {
        continue;
    }
    var reader = new FileReader();
    // Closure to capture the file information.
    reader.onload = (function(theFile) {
        return function(e) {
            // Render thumbnail.
         var span = document.createElement('span');
span.setAttribute('class', 'spin');
                  span.innerHTML = ['<img class="thumb" src="', e.target.result,
                                    '" title="', escape(theFile.name), '"/>'].join('');
        document.getElementById('list').insertBefore(span, null);
        };
    })(f);


    // Read in the image file as a data URL.
    reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
//</script>

最佳解决方案:

不要使用重复的ID

根据HTML规范,ID应该是文档中唯一的。

你会注意到API引用了:

document.getElementById——注意奇异元素

你最好使用CSS类名并从中选择,或者使用data-属性,并从中选择。

如果您坚持使用重复的ID:

document.querySelectorAll("#list");——这将处理多个id的无效代码。

按注释更新

document.getElementsByClassNamedocument.querySelectorAll都返回一个节点列表——一个必须循环通过的类数组结构。

从你的用法来看,似乎你来自jQuery背景,它隐藏了所有的东西,从把所有东西变成一个数组,并应用jQuery方法到该数组。

当试图弄清楚为什么某些东西在JavaScript中不起作用时,查看值have总是一个好主意。这会告诉你很多。

var nodeList = document.querySelectorAll("#list");
console.log(nodeList);
console.log(nodeList.toString());
for (var i = 0; i < nodeList.length; i++) {
  var node = listList[i];
   var span = document.createElement("span");
   span.appendChild(document.createTextNode("A span!");
   node.insertBefore(span, null)
}

这招奏效了。谢谢!

<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>

<script>
 window.preview = function (input) {
if (input.files && input.files[0]) {
    $(input.files).each(function () {
        var reader = new FileReader();
        reader.readAsDataURL(this);
        reader.onload = function (e) {
            $(".list").append("<img class='thumb' src='" + e.target.result + "'>");
        }
    });
}

}

http://jsfiddle.net/qF7Ff/1/