日期:2014-05-16 浏览次数:20325 次
?
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<button class="button">1</button>
<button class="button">2</button>
<button class="button">3</button>
<button class="button">4</button>
<button class="button">5</button>
<button class="button">6</button>
<button class="button">7</button>
<button class="button">8</button>
<button class="button">9</button>
<script type="text/javascript">
? var nodes=document.getElementsByTagName("button");
? var clickButton=function(nodes){
?var i;
?for(i=0;i<nodes.length;i++){
? ? ? ? ? ?nodes[i].onclick=function(){alert(i);};
?}
?}
?clickButton(nodes);
?
</script>
</body>
</html>
?
由于js事件处理器执行时绑定变量i,导致点击任意按钮,都alert出最后的 i值8;而不是函数构造是i的值;
?
用闭包可解决这个问题,js改为
?
<script type="text/javascript">
? var nodes=document.getElementsByTagName("button");
?
var clickButton2=function(nodes){
? ? ?var i;
for(i=0;i<nodes.length;i++){
? ? ?nodes[i].onclick=function(){
var e=i;
return function(){alert(e);};
?}();
?
}
};
?
clickButton2(nodes);
</script>
?
便可达到预期效果
?