以下代码从xml文件获取信息。我成功地使用按钮呈现了每个行星的id和名称。
我想在按钮上添加一个onclick事件。 问题是:它确实添加了onclick事件,但仅在循环中创建的最后一个按钮上。
我做错了什么?为什么它不为每个按钮创建一个onclick事件,而只为循环中的最后一个按钮创建一个?
我想在按钮上添加一个onclick事件。 问题是:它确实添加了onclick事件,但仅在循环中创建的最后一个按钮上。
我做错了什么?为什么它不为每个按钮创建一个onclick事件,而只为循环中的最后一个按钮创建一个?
function updatePlaneten() {
var valDiv, planets, valButton, textNode;
// Get xml files
planets = this.responseXML.getElementsByTagName("planeet");
// loop through the <planet> tags
for (var i = 0; i < planets.length; i++) {
valDiv = ''; // clear valDiv each time loop starts
// Get the id and the name from the xml info in current <planet> tag
valDiv += planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue + "<br>";
valDiv += planets[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + "<br>";
document.getElementById("planetenID").innerHTML += valDiv + "<br>";
// Create button with a value and pass in this object for later reference use (valButton.object=this)
valButton = document.createElement("input");
// valButton.setAttribute("planeetID", planets[i].getElementsByTagName("id")[0].childNodes[0].nodeValue);
valButton.setAttribute("value", 'Meer info');
valButton.setAttribute("type", 'button');
valButton.id = (i + 1);
valButton.object = this;
//
// Here is the problem i cant get fixed
//
//valButton.onclick = function(){ showinfo(); }
valButton.addEventListener('click', showinfo);
// Place the button on screen
document.getElementById("planetenID").appendChild(valButton);
}
}
// simple function to check if it works
function showinfo() {
console.log(this.object);
console.log(this.id);
}