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

如何为使用JavaScript动态创建的图像按钮提供id?,javascript,html,css,json,imagebutton,Javascript,Html,Css,Json,Imagebutton,我是JavaScript的新手,我有一个JavaScript,它可以在HTML页面上创建8个图像按钮。我想在每个生成的imagebutton中插入一个函数,该函数可以返回一个特定的id,但问题是当我单击任何按钮时,我只得到id:8。但我想要id:1作为第一个按钮,以此类推。 数据={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

我是JavaScript的新手,我有一个JavaScript,它可以在HTML页面上创建8个图像按钮。我想在每个生成的imagebutton中插入一个函数,该函数可以返回一个特定的id,但问题是当我单击任何按钮时,我只得到id:8。但我想要id:1作为第一个按钮,以此类推。 数据={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);
}

for(var i=0;i这有一个非常简单的修复方法

在“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在我之前的评论中这样做了,所以从技术上讲,我不应该因为这个答案得到任何赞扬。

这有一个非常简单的解决方法

在“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在我之前的评论中这样做了,所以从技术上讲,我不应该因为这个答案而得到任何赞扬。

可能重复的是,这是一个关闭问题。在所有单击侦听器中,myButton引用了最后一个按钮。请改用
this.id
。可能重复的是,这是一个关闭问题假设在所有单击侦听器中,myButton引用最后一个按钮。请改用
this.id