Ich bin ein Neuling zu JavaScript, und ich habe ein JavaScript, das 8 Bildschaltflächen zu einer HTML-Seite erstellt. Ich möchte eine Funktion in jede generierte Bildschaltfläche einfügen, die eine bestimmte ID zurückgeben könnte, aber das Problem ist, wenn ich auf eine Schaltfläche klicke, bekomme ich nur ID: 8. Aber ich möchte ID: 1 für den ersten Button und so weiter. data = {id: 1, ID: 2 ..... ID: 8} und einige BildWie gebe ich einer dynamisch mit JavaScript erstellten Bildschaltfläche eine ID?
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);
}
Mögliche Duplikate von [JavaScript-Abschluss in Schleifen - einfaches praktisches Beispiel] (http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Teemu
Ja, es ist ein Schließproblem . In allen Klick-Listenern verweist * myButton * auf die letzte Schaltfläche. Verwenden Sie stattdessen "this.id". – RobG