javascript使用for循环批量注册的事件不能正确获取索引值的解决方法


本文实例讲述了javascript使用for循环批量注册的事件不能正确获取索引值的解决方法。分享给大家供大家参考。具体分析如下:

可能不少朋友会遇到一个问题,那就是当使用for循环批量注册事件处理函数,然后最后通过事件处理函数获取当前元素的索引值的时候会失败,先看一段代码实例:

复制代码 代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.phpstudy.net/" />
<title>phpstudy</title>
<style type="text/css">
li{
  width:240px;
  overflow:hidden;
  text-overflow:ellipsis;
  white-space:nowrap;
  font-size:12px;
  height:30px;
}
</style>
<script type="text/javascript">
window.onload=function(){
  var oLis=document.getElementsByTagName("li");
  var oshow=document.getElementById("show");
  for(var index=0;index<oLis.length;index++){
    oLis[index].onclick=function(){
      oshow.innerHTML=index;
    }
  }
}
</script>
</head>
<body>
<div id="show"></div>
<ul>
  <li>只有努力奋斗才会有美好的明天。</li>
  <li>分享互助是进步最大的源动力。</li>
  <li>每一天都是新的,要好好珍惜。</li>
  <li>没有人一开始就是高手,只有努力才有成长的可能</li>
  <li>只有当下的时间是可贵的,下一秒都是虚幻的</li>
</ul>
</body>
</html>

在上面的代码中,当点击li元素的时候弹出值始终是四,我们本来的想法是,点击li元素在div中显示当前li元素的索引值,下面就简单分析一下其中的原因。原因非常的简单,当for循环执行完毕以后,index的值已经变为四,于是也就出现了上面的现象。
代码修改如下:

复制代码 代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.phpstudy.net/" />
<title>phpstudy</title>
<style type="text/css">
li{
  width:240px;
  overflow:hidden;
  text-overflow:ellipsis;
  white-space:nowrap;
  font-size:12px;
  height:30px;
}
</style>
<script type="text/javascript">
window.onload=function(){
  var oLis=document.getElementsByTagName("li");
  var oshow=document.getElementById("show");
  for(var index=0;index<oLis.length;index++){
    oLis[index]._index=index;
    oLis[index].onclick=function(){
      oshow.innerHTML=this._index;
    }
  }
}
</script>
</head>
<body>
<div id="show"></div>
<ul>
  <li>只有努力奋斗才会有美好的明天。</li>
  <li>分享互助是进步最大的源动力。</li>
  <li>每一天都是新的,要好好珍惜。</li>
  <li>没有人一开始就是高手,只有努力才有成长的可能</li>
  <li>只有当下的时间是可贵的,下一秒都是虚幻的</li>
</ul>
</body>
</html>

上面的代码实现了我们的要求,当然也可以使用闭包的方式,代码如下:

复制代码 代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.phpstudy.net/" />
<title>phpstudy</title>
<style type="text/css">
li{
  width:240px;
  overflow:hidden;
  text-overflow:ellipsis;
  white-space:nowrap;
  font-size:12px;
  height:30px;
}
</style>
<script type="text/javascript">
window.onload=function(){
  var oLis=document.getElementsByTagName("li");
  var oshow=document.getElementById("show");
  for(var index=0;index<oLis.length;index++){
    (function(index){
      oLis[index].onclick=function(){
        oshow.innerHTML=index;
      }
    })(index)
  }
}
</script>
</head>
<body>
<div id="show"></div>
<ul>
  <li>只有努力奋斗才会有美好的明天。</li>
  <li>分享互助是进步最大的源动力。</li>
  <li>每一天都是新的,要好好珍惜。</li>
  <li>没有人一开始就是高手,只有努力才有成长的可能</li>
  <li>只有当下的时间是可贵的,下一秒都是虚幻的</li>
</ul>
</body>
</html>

希望本文所述对大家基于javascript的web程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3