2014-10-07 92 views
3

我目前正在学习DOM,并遇到两个或多个克隆元素获取相同事件侦听器时遇到的这个问题。如何将侦听器附加到克隆的元素?

 case 116: 
      var myList = document.querySelectorAll(".selected"); 
      for(var i=0; i<myList.length;i++) 
      { 
       var node=myList[i].cloneNode(true); 
       node.style.top=Math.random()*window.innerHeight-(node.style.height/2)+"px"; 
       node.style.left=Math.random()*window.innerWidth-(node.style.width/2)+"px"; 
       node.addEventListener("click",function(e){ 
        node.classList.toggle("selected"); 
        console.log(e); 
       }); 
       myList[i].parentNode.appendChild(node); 
      } 
      break; 

the code

箱1的原包装盒,它有它自己的事件监听。

框2是原始的克隆,并选择和取消选择,因为它应该。

盒3-4是1-2的克隆,但似乎箱3和4得到相同的监听器,因为当我上 箱4点击切换选择上盒3并没有什么用箱发生4

我该如何解决这个问题?

任何帮助将是最受欢迎的。

+0

什么是初始状态?是否只有一个框,并且使用此代码添加框2,3和4?迭代这个代码来获得可见效果多少次? – STT 2014-10-07 12:49:13

+0

初始状态是一个盒子。正确。 两次迭代产生上面的图片。 – ogward 2014-10-07 13:02:06

回答

1

我认为这是一个范围界定问题。您的事件处理程序正在参考node,但在循环结束时,node将指向创建的最后一个正方形。您可以存储的node值使用封闭每个事件处理程序:

(function(node) { 

    // 'node' defined here is in it's own scope, so won't be affected by the changes 
    // made to the 'node' variable defined in the outer scope of the loop. 
    node.addEventListener("click",function(e){ 
     node.classList.toggle("selected"); 
     console.log(e); 
    }); 

})(node); 

,但可能是更好的解决方案是你的事件处理程序中使用this

node.addEventListener("click",function(e){ 

    // within an event handler, 'this' references the event's target element 
    this.classList.toggle("selected"); 
    console.log(e); 
}); 
+0

感谢您的帮助,它就像一个魅力! – ogward 2014-10-07 13:02:51

相关问题