从文件输入返回两个图像跨度

时间:2016-05-16 20:46:14

标签: javascript html

我有以下JavaScript代码:

    <script>
    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.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>

底线的EventListener是侦听输入文件HTML元素。选择文件后,handeFileSelect函数将执行其余操作。现在它将跨度返回到我的'列表'。我想要的是制作另一个列表,它不必具有相同的ID,但需要像其他列表一样填充。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

我认为您应该只需要重复添加图像的代码,以便将其添加到第二个列表中。

        reader.onload = (function(theFile) {
            return function(e) {
                // Render thumbnail.
                var span = document.createElement('span');
                span.innerHTML = ['<img class="thumb" src="', e.target.result,
                    '" title="', escape(theFile.name), '"/>'].join('');
                document.getElementById('list').insertBefore(span, null);
                var span2 = document.createElement('span');
                span2.innerHTML = ['<img class="thumb" src="', e.target.result,
                    '" title="', escape(theFile.name), '"/>'].join('');
                document.getElementById('list2').insertBefore(span2, null);
            };
        })(f);

DEMO