简体   繁体   中英

How to give an id to a image button dynamically created using JavaScript?

I am a newbie to JavaScript, and I am having a JavaScriptwhich creates 8 image buttons to a HTML page. I want to insert a function in each generated imagebutton which could return a particular id, but the issue is when I click any button I am getting only id:8. But I want id:1 for first button and so on. data= {id:1,id:2.....id:8} and some image

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

This has a really easy fix.

In your 'onclick' function, don't refer to the button by it's variable name. Replace the variable name "myButton" with 'this':

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

EDIT:I saw I wasn't the first one to solve your issue. @RobG did it in the comments before me So technically I shouldn't get any credit for this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM