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

标签 javascript html css json imagebutton

我是 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/

相关文章:

javascript - 即使从另一个 HTML 页面重定向后,仍保留 HTML 中的表单值

javascript - 如何在运行脚本之前检查元素是否已加载到页面上?

css - 我网站的 CSS 何时会影响我的搜索引擎排名?

jquery - 使用复选框显示/隐藏表格中的行

html - 无法在每个按钮下正确显示标签?

javascript - Pg-promise - 可能参与事务/任务的可重用查询

javascript - AngularJS : table colspan rowspan dynamic calculation

javascript - xpages 中的 Lotus Notes 客户端链接和浏览器链接用于下载服务器目录中存储的文件

javascript - 如何将 mailerlite.com 注册表单与 React 集成?

javascript - 将 "selected"属性添加到不同选择 "tag"中的选项