【问题标题】:How to give an id to a image button dynamically created using JavaScript?如何为使用 JavaScript 动态创建的图像按钮提供 id?
【发布时间】: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);
}

【问题讨论】:

标签: javascript html css json imagebutton


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    相关资源
    最近更新 更多