【发布时间】:2017-01-13 22:10:07
【问题描述】:
我是 JavaScript 的新手,我有一个 JavaScript,它可以为 HTML 页面创建 8 个图像按钮。我想在每个生成的图像按钮中插入一个函数,该函数可以返回一个特定的 id,但问题是当我单击任何按钮时,我只得到 id:8。但我想要第一个按钮的 id:1 等等。 data= {id:1,id:2.....id:8} 和一些图片
for(var i=0;i<8;i++){
var x=data[i].image; //this is the image I gets from a JSON string
var y=data[i].name; //this is the name I gets from a JSON string
var id=data[i].id; //this is the id I gets from a JSON string
var body = document.getElementsByTagName("body")[0];
var myButton = document.createElement("input");
myButton.src=x;
myButton.name=String(id);
myButton.id=data[i].id;
myButton.type = "image";
body.appendChild(myButton);
//i need help with below section
myButton.onclick = function(){
console.log("this is my id ",myButton.id);
//this function will return only the`data[8].id every time
};
console.log(x);
console.log(y);
console.log(id);
}
【问题讨论】:
-
是的,这是一个关闭问题。在所有点击监听器中,myButton 引用最后一个按钮。请改用
this.id。
标签: javascript html css json imagebutton