如何将onclick事件添加到在javascript中创建的img元素

时间:2018-05-09 09:36:24

标签: javascript

基本上创建一个包含用户上传的图像和名称的表,现在我想让用户通过onclick事件选择他想要的图像,但是一旦我上传图像功能" myfunction&#34 ;在没有点击img的情况下运行

function handleFiles(){

var inputElement = document.getElementById("input");

var fileList = inputElement.files; 

var NameFile = [];

for(var i = 0; i < fileList.length; i++){

NameFile=fileList[i].name;

var x = document.createElement("Table");
x.setAttribute("id", "galeria" + (i));
document.body.appendChild(x);

//图片

var Img = document.createElement("tr");
Img.setAttribute("id", "ImgTr" +(i));
document.getElementById("galeria" +(i)).appendChild(Img);

var Imgz = document.createElement("td");
var img =document.createElement("img");

img.src = window.URL.createObjectURL(fileList[i]);
  img.height = 50;
  img.onload = function(){
    window.URL.revokeObjectURL(this.src);
  }

  img.onclick = myfunction(); // onclick event attateched to img 
  element

Imgz.appendChild(img);
document.getElementById("ImgTr" + (i)).appendChild(Imgz);

//文件名

var y = document.createElement("tr");
y.setAttribute("id", "Tr" + (i));
document.getElementById("galeria" +(i)).appendChild(y);

var z = document.createElement("td");
var t = document.createTextNode(NameFile);
z.appendChild(t);
document.getElementById("Tr" + (i)).appendChild(z);

}
}


function myfunction(){
alert("hello");
}

1 个答案:

答案 0 :(得分:0)

感谢@CertainPerformance

解决了问题
/.../

img.onclick = myfunction; // onclick event attateched to img 
element

/.../