【问题标题】:Return two image spans from file input从文件输入返回两个图像范围
【发布时间】:2016-05-16 20:46:13
【问题描述】:

我有以下一段 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,但它需要完全像另一个列表一样填充。我该怎么做?

【问题讨论】:

  • 不确定我是否理解。只需创建另一个跨度,并将其插入到 list2 之前。
  • 返回函数里面?试过了,但它只出现在两个列表之一中。

标签: javascript html


【解决方案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

【讨论】:

  • 我试过这个,但它使图像只出现在最后一个给定的列表中。所以在这种情况下,图像只会显示在 list2 中。我通过创建一个递归函数来解决我的问题,在我看来这是一个非常丑陋的解决方案。我现在在工作,无法与您分享我的代码,但我会在回家时更新您。
  • 我不明白如何附加两个不同的跨度并将它们插入两个不同的列表会导致只显示一个图像,除非你有隐藏其中一个的 CSS。你能做一个演示问题的jsfiddle吗?
  • 你好 Barmar,你可以在这里找到 JsFiddle:jsfiddle.net/ohs25kpx/2。我包括了你的解决方案,可能我忽略了一些东西..
  • 我打错了,第二个insertBefore 应该插入span2,而不是span
  • 我不敢相信我自己也监督了这件事。尝试了很多像你这样的选择,但都没有奏效。非常感谢巴尔玛!
猜你喜欢
  • 1970-01-01
  • 2016-10-11
  • 2012-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-26
相关资源
最近更新 更多