闭包
解决方法如下
for (var i = 1 ; i < 4;i ++) {
var obj = document.getElementById('item' + i); 
obj.attachEvent('onmouseover',
function (o) {
return function (e) { hightlight(o); }
}(obj)
); 
obj.attachEvent('onmouseout',
function (o) {
return function (e) { normal(o); }
}(obj)
);

解决方案 »

  1.   

    一见到function包function我就晕,还没消化,学习。
      

  2.   

    循环的过程中。。
    var obj = document.getElementById('item' + i); 
    一直在改变,而那些function里引用的正是obj
    所以,一直到循环结束
    obj 的最后结果是最后一次循环的结果。。
    所以
    所有遍历的function里都是引用的最后一次的obj的结果而闭包,则重新复制了每次循环的obj的引用,每次的function引用了复制的那些变量。
    所以,实现了效果关于闭包
    http://blog.csdn.net/muxrwc/archive/2007/11/09/1876342.aspx
    这里有介绍
    也可以去google or baidu 上艘下:D
      

  3.   

    IE里面的attachEvent是有点不爽 本来事件方法执行时this应该是本元素实例 但IE下却是window 没法只能用闭包给事件方法一个相对独立的变量参数才能访问
    <!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=gb2312" />
    <title> 无标题文档 </title></head><body>
    <table width="100%" border="1" cellspacing="0" cellpadding="0">
      <tr>
        <td id="item1">&nbsp;  </td>
      </tr>
      <tr>
        <td id="item2">&nbsp;  </td>
      </tr>
      <tr>
        <td id="item3">&nbsp;  </td>
      </tr>
    </table>
    </body>
    </html> 
    <script language="javascript">
    function hightlight(o)
    {
    o.style.backgroundColor='#999999';
    }
    function normal(o)
    {
    o.style.backgroundColor='';
    }
    function addEvent(obj)
    {
    //这里就是闭包 参数obj在这个闭包里是相对独立的
    obj.attachEvent('onmouseover',function(){hightlight(obj);});
    obj.attachEvent('onmouseout',function(){normal(obj);});
    }
    for(var i=1;i<=3;i++)
    addEvent(document.getElementById('item'+i));</script>
      

  4.   

    呃,带来的另一个问题是,不能detachevent