加载图像预览的脚本不起作用

时间:2016-12-20 14:57:07

标签: javascript jquery addeventlistener

我为show images创建脚本,直到上传,我如何使用5个输入文件进行上传,脚本必须让一个图像显示,或者为每个输入文件预览图像

剧本:

<script>
function handleFileSelect(evt,ids) {
  var files = evt.target.files;
  var f = files[0];
  var reader = new FileReader();

  reader.onload = (function(theFile) {
    return function(e) {
      document.getElementById('list'+ids).innerHTML = ['<img src="', e.target.result,'" title="', theFile.name, '" width="50"/>'].join('');
      ///alert("ok"+ids);
    };
  })(f);

  reader.readAsDataURL(f);
}
</script>

HTML CODE

<input type="file" id="files2" />
<output id="list2"></output>

为此输入文件ID调用脚本

<script>
document.getElementById('files2').addEventListener('change', function(){handleFileSelect('','2');},false);
</script>

正如你所看到的那样,我尝试从 handleFileSelect('','2')发送变种,但是从来没有工作过,我觉得代码很好,但我确定忘了什么,我希望这里可以帮助我解决这个问题,感谢社区

最好的问候

2 个答案:

答案 0 :(得分:0)

试试此代码

$('#ifdivider').mousedown(function(e) {

    isDragging = true;
    xOffset = e.pageX;
    console.log('down');

    $(document).one('mouseup', function() {
        isDragging = false;
        $(document).off('mousemove.dragging');
        console.log('up');            
    });

    $(document).on('mousemove.dragging', function(e) {       
        if (isDragging && e.pageX < 500) {
            $('#ifmenu').css('width',e.pageX - 2);
            console.log('move');            
        }
    });
});
notfound

答案 1 :(得分:0)

如果你使用CreateObjectURL更好(节省更多内存/ cpu)它也是faster

var wrapper = document.getElementById('files')
var URL = window.URL || window.webkitURL;

wrapper.addEventListener('change', function(evt){
  var input = evt.target
  
  if (input.matches('input[type="file"]') && (input.files || [])[0]) {
    var img = new Image
    img.width = 50
    img.onload = function() {
      var output = document.getElementById(input.dataset.for)
      output.appendChild(this)
    }
    img.onerror = function(){
      console.log("You uploaded something that is not an image")
    }
    img.src = URL.createObjectURL(input.files[0])
  }
})
output {
  display: block;
}
<div id="files">
  
  <!-- Recomend adding accept attribute so you only get images -->
  <!-- just made one example -->
  <input type="file" data-for="list1" accept="image/*">
  <output id="list1"></output>

  <input type="file" data-for="list2">
  <output id="list2"></output>

  <input type="file" data-for="list3">
  <output id="list3"></output>

  <input type="file" data-for="list4">
  <output id="list4"></output>

</div>