I am creating buttons dynamically in JavaScript. Also adding dynamically an eventhandler to each button. For the last button it works but the previous ones simply are not working any longer. Here's my small piece of code. What do I do wrong?
<html>
<head>
<script>
var id = 0;
function makeFunc(arg) {
return function() {
alert('selected ' + arg)
}
};
function addElement() {
document.getElementById('p1').innerHTML +=
'<button id=\'id' + id + '\'>Button' + id + '</button>';
document.getElementById('id' + id).onclick = makeFunc(id);
id++;
}
</script>
</head>
<body>
<button onclick="addElement();">Add Button</button>
<p id="p1"></p>
</body>
</html>
it's also here: http://jsfiddle.net/q52a7fw0/
When you use
innerHTML
likeyou overwrite exisiting event handlers.
Instead, you should create the element and append it