求高手帮忙看下这个简单的事件处理
想通过js动态创建节点,循环创建几个按钮,给每个按钮都添加上事件,点击按钮就分别弹出数组里的数据
反复折腾也实现不了,求帮助!!!
<html>
<head>
<script>
count = 0;
var array = [];
array.push(1);
array.push(2);
array.push(3);
array.push(4);
array.push(5);
window.onload=function(){
mybody = document.getElementsByTagName("body")[0]; //得到Body节点
for(var i = 0;i<5;i++){
newB = document.createElement("input"); //创建节点
newB.type = "button";
newB.value = i;
newB.name = "button1"; //设置属性
mybody.appendChild(newB); //添加进Body
}
var bb = document.getElementsByTagName("input"); //得到所有的button
for(var i = 0 ; i<bb.length;i++){
bb[i].onclick = function(){
alert(array[count]);
}
count++;
//这里不行,求帮助
}
}
</script>
</head>
<body>
</body>
</html>
还是我的思路有问题吗?求大家帮忙解决下!
------解决方案--------------------<html>
<head>
<script>
count = 0;
var array = [];
array.push(1);
array.push(2);
array.push(3);
array.push(4);
array.push(5);
window.onload = function() {
mybody = document.getElementsByTagName("body")[0]; //得到Body节点
for ( var i = 0; i < 5; i++) {
newB = document.createElement("input"); //创建节点
newB.type = "button";
newB.value = i;
newB.name = "button1"; //设置属性
mybody.appendChild(newB); //添加进Body
}
var bb = document.getElementsByTagName("input"); //得到所有的button
for ( var i = 0; i < bb.length; i++) {
bb[i].onclick = (function() {
var count = i;
return function(){
alert(array[count]);
}
})()
}
}
</script>
</head>
<body>
</body>
</html>