javascript 尝试访问 <input> 文件时无法读取未定义的属性“目标”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12628649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:42:25  来源:igfitidea点击:

Cannot read property 'target' of undefined when trying to access <input> files

javascriptfile-uploadfilereader

提问by Tony Medina

I'm trying to change file upload image to select or click on image on the same page in this canvas related script.

我正在尝试更改文件上传图像以选择或单击此画布相关脚本中同一页面上的图像。

function aFileIsLoaded(e1)
{
        var filename = e1.target.files[0];
        var fr = new FileReader();
fr.onload = function(e2)
{
      backgroundimage = new Image();
      backgroundimage.src=e2.target.result;
     var context = document.getElementById('myCanvas').getContext('2d');
     context.canvas.width = backgroundimage.width;
     context.canvas.height = backgroundimage.height;
     context.drawImage(backgroundimage, 0, 0, backgroundimage.width, backgroundimage.height);


};
    fr.readAsDataURL(filename);
}



window.onload=function(){
var s = document.getElementById("fontsize");
s.value="48";
document.getElementById('loadpicture').addEventListener('change', aFileIsLoaded, false);
backgroundimagemode=NONE;
carpeInit();
update();
}

before, this images were called like this, and files were selected from desktop

以前,这个图片是这样调用的,文件是从桌面选择的

<input type="file" name="back" id="loadpicture" src="myimage.png" >

and now I'm trying to load an image in the same page with this:

现在我正在尝试使用以下内容在同一页面中加载图像:

<img src="myimage.png" name="back" id="loadpicture" onclick="aFileIsLoaded()">

but I'm getting this error:

但我收到此错误:

Uncaught TypeError: Cannot read property 'target' of undefined 

any help will be appreciated

任何帮助将不胜感激

回答by Mikko Ohtamaa

You are calling a custom function:

您正在调用自定义函数:

function aFileIsLoaded(e1)
{
        var filename = e1.target.files[0];

This function expects an Event object instance, of a file input change event, to be passed as its first and only argument. You do not pass this parameter e1in your onclickhandler

此函数期望文件输入更改事件的 Event 对象实例作为其第一个也是唯一的参数传递。你没有在你的onclick处理程序中传递这个参数e1

 onclick="aFileIsLoaded()">

The workaround is to use DOM look-up to look the element in the question to read its files

解决方法是使用 DOM 查找来查找问题中的元素以读取其文件

 var filename = document.getElementById('loadpicture').files[0]

As the example lacks HTML code the answer might not be complete.

由于示例缺少 HTML 代码,因此答案可能不完整。

More information abouts the events

有关活动的更多信息

https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener

https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener