[收藏]Javascript循环元素并绑定事件

废话不多说,直接上代码!具体原理请参考JS闭包原理

<!DOCTYPE html PUBLIC ”-//W3C//DTD XHTML 1.0 Transitional//EN” ”http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=“http://www.w3.org/1999/xhtml” >
<head>
<title>Untitled Page</title>
</head>
<body>
<ul id=“list”>
<li>第1条记录</li>
<li>第2条记录</li>
<li>第3条记录</li>
<li>第4条记录</li>
<li>第5条记录</li>
<li>第6条记录</li>
</ul>

<script type=“text/javascript”>
var list_obj = document.getElementById(“list”).getElementsByTagName(“li”); //获取list下面的所有li的对象数组
for (var i = 0; i <= list_obj.length; i++) {
(function(){
var p = i
list_obj[i].onmousemove = function() {
this.style.backgroundColor = “#cdcdcd”;
}
list_obj[i].onmouseout = function() {
this.style.backgroundColor = “#FFFFFF”;
}
list_obj[i].onclick = function() {
alert(“这是第” + p + “记录”);
}
})()
}
</script>

</body>
</html>
  1. 感谢分享!超级赞!

  1. 暂无 Trackback

return top