<head lang="en"> <meta charset="UTF-8"> <title></title> <script type="text/javascript"> window.onload = function () { var aUl = document.getElementById("bubble"); var aLi = aUl.getElementsByTagName("li"); for(var i = 0; i < aLi.length; i++) { aLi[i].onmouseover = function () { this.style.backgroundColor = "blue"; }; aLi[i].onmouseout = function () { this.style.backgroundColor = ""; } aLi[i].onclick = function () { alert(aLi[i]); } } }; </script> </head> <body> <div> <ul id = "bubble"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> </div> </body>
通过for循环可以实现事件的绑定,但是又与作用链的存在,又导致了一个经典问题
这里当你点击li标签的时候,都返回undefined,而不是说对应的0,1,2,3。因为变量无法贮存在内存当中。
解决这个问题有三种方式:(1)闭包,(2)添加新的属性,(3)事件委托
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
window.onload = function () {
function addEvent(doc, lab, eventarg, func) {
if (window.addEventListener) {
doc.addEventListener(eventarg, function (evt) {
var ev = evt;
var tag = ev.target;
if (tag.nodeName.toLowerCase() == lab.toLowerCase()) {
func(tag);
}
}, false);
}
else if (window.attachEvent) {
doc.attachEvent('on'+eventarg, function (evt) {
var ev = window.event;
var tag = ev.srcElement;
if (tag.nodeName.toLowerCase() == lab.toLowerCase()) {
func(tag);
}
});
}
}
var uls = document.getElementById('bubble');
function test(tag) {
alert(tag.innerHTML);
}
addEvent(uls, 'li', 'click', test);
};
</script>
</head>
<body>
<div>
<ul id = "bubble">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
</body>
这里就写了一个事件委托的解决方式。