JavaScript弄乱了OnChange文件输入 [英] JavaScript Messed up OnChange File Input

查看:69
本文介绍了JavaScript弄乱了OnChange文件输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么网络技术如此混乱. 我正在尝试完成一些非常简单的事情.但是发现它有错误.

I do not understand why web technology is so messed up. I am trying to accomplish something really easy. But found out that it has bugs.

所以我想做的是在div中加载用户选择的图像.它是第一次工作.但是,一旦我选择浏览并选择另一个图像,它就不起作用了.这是怎么了

So what I am trying to do is load in a div the image selected by user. It works first time. But once I select browse and select another image it doesn't work. What is wrong here?

<input type="file" id="imgUploadButton" class="default" name="picture" onchange="imageUploaded(event);" />

这是Javascript代码

And this is the Javascript code

var selectedFile = event.target.files[0];
var reader = new FileReader();
var imgtag = document.getElementById("imageTool");

imgtag.title = selectedFile.name;
reader.onload = function(event) {
    imgtag.src = event.target.result;
 };
 reader.readAsDataURL(selectedFile);

推荐答案

如果我是我,我会定义onchange事件,例如,通过执行以下操作:

I would define the onchange event a bit differently if I were you, for example by doing the following:

<input type="file" id="imgUploadButton" />
<div><img id="imageTool" /></div>
<script>
  // Create a self-executing anonymous function so that the window
  // isn't being cluttered with global variables
  (function() {
    // First get the file element
    var fileElement = document.getElementById('imgUploadButton');

    // Now if we found the file element, add the onchange event, 
    // doing it like this maximizes compatibility
    if (fileElement) fileElement.onchange = imageUploaded;

    // Define your imageUploaded function, as it will get hoisted
    // anyway
    function imageUploaded(event) {
      var selectedFile = event.target.files[0];
      var reader = new FileReader();
      var imgtag = document.getElementById("imageTool");
      imgtag.title = selectedFile.name;
      reader.onload = function(event) {
        imgtag.src = event.target.result;
      };
      reader.readAsDataURL(selectedFile);
    }
  }());
</script>

当然,

最好是在body标记的末尾执行此操作.在这里查看我的 jsfiddle .

Best is to do this on the end of the body tag, of course. See my jsfiddle here.

这篇关于JavaScript弄乱了OnChange文件输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆