2014-10-07 96 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

相關問題