JS实现循环给元素绑定事件

        作为一个前端开发者,如果想对一些元素循环绑定事件的时候总是出现各种问题,尤其是在对闭包没有熟练掌握的时候更是一头雾水。网上一查,果然好多初学者有这个困惑,既然这个问题总是出现,于是在我就总结了以下两个比较好理解的解决方案,分享给大家:(可能有更好的方式我没有发现,请各位分享)。

HTML代码:

<div class="textwidget">  
        <span  class="textwidget">第一个</span>  
        <span  class="textwidget">第二个</span>  
        <span  class="textwidget">第三个</span>  
</div>

JS代码:

window.onload = function()   
{               
      var  spans = document.getElementsByClassName("textwidget");
      for(var i = 1; i < spans.length; i++)   
      {  
        spans[i].count = i;  
        spans[i].onmouseover = function()   
        {          
                this.style['margin-top'] = '-145px';
                this.style.display='block';     
        }
        spans[i].onmouseout = function()   
        {          
                this.style['margin-top'] = '0px';
                this.style.display='none';     
        }     
      }   
}

发表评论?

0 条评论。

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.