gpt4 book ai didi

javascript - 如何为使用 JavaScript 动态创建的图像按钮提供 id?

转载 作者:行者123 更新时间:2023-11-28 05:07:13 25 4
gpt4 key购买 nike

我是 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);
}

最佳答案

这有一个非常简单的修复。

在“onclick”函数中,不要通过变量名称引用按钮。将变量名“myButton”替换为“this”:

myButton.onclick = function(){
console.log("this is my id ",this.id);
//this function will return only the`data[8].id every time
};

编辑:我发现我不是第一个解决您的问题的人。 @RobG 在我之前的评论中做到了,所以从技术上讲,我不应该因为这个答案而获得任何荣誉。

关于javascript - 如何为使用 JavaScript 动态创建的图像按钮提供 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41644223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com