我正在尝试使用 for 循环使用独特的侦听器和处理程序动态创建按钮,但不幸的是我一定做错了,因为只有最后一个按钮有效。更令人惊讶的是,当单击最后一个按钮而不是“Button No.3”时,它会返回“Button No.4”
贝娄是代码,这里是一个 jsfiddle http://jsfiddle.net/y69JC/4/
HTML:
<body>
<div id="ui">
some text ...
</div>
</body>
Javascript:
var uiDiv = document.getElementById('ui');
uiDiv.innerHTML = uiDiv.innerHTML + '<br>';
var results = ["Button one","Button two","Button three","Button four"];
for(var n=0;n<results.length;n++)
{
uiDiv.innerHTML = uiDiv.innerHTML + '<button id="connect'+n+'">option'+n+':'+results[n]+'</button><br>';
var tempId = document.getElementById('connect'+n);
tempId.addEventListener('click', function(){console.log("Button No."+n)}, false);
}
谢谢!