日期:2014-05-20  浏览次数:21039 次

第一次发现js批量绑定事件,竟然会出问题。。。。
HTML code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
 </HEAD>
<script type="text/javascript">
 window.onload = function() 
 {
   var spans = document.getElementsByName("tst");
   for(var i = 0;i<spans.length;i++)
   {
        var span = spans[i];
        span.onclick =function(){alert(i)};
   }
 }
</script>

<BODY>
<input type="button" name="tst" />
<input type="button" name="tst" />
<input type="button" name="tst" />
</BODY>
</HTML>





求一种解决方式。
不使用jQuery插件。。。。。

------解决方案--------------------
楼主弹出的都是3逻辑上是正确的。绑定完了之后i的值已经是3了,所以执行的时候只可能会弹出三。

------解决方案--------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
 </HEAD>
<script type="text/javascript">
 window.onload = function() 
 {
var spans = document.getElementsByName("tst");
for(var i = 0;i<spans.length;i++)
{
var span = spans[i];
(function(){
var ii = i;
span.onclick =function(){alert(ii.toString() + this.id)};
})();
}
 }

function check()
{
var button1 = document.getElementById('test1');
var button2 = document.getElementById('test2');
var button3 = document.getElementById('test3');
alert(button1.onclick);
alert(button2.onclick);
alert(button3.onclick);

}
</script>

<BODY>
<input type="button" name="tst" id="test1" />
<input type="button" name="tst" id="test2" />
<input type="button" name="tst" id="test3" />
<br/>

<input type="button" name="check" onclick="javascript:check();"/>
</BODY>
</HTML>

闭包的原因