[英]How do I attach a listener to a cloned element?
I'm currently learning about DOMs and have this problem I'm struggling with when two or more cloned elements get the same event listener. 我目前正在学习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;
box 1 is the original box and it has its own EventListener. 框1是原始框,它有自己的EventListener。
box 2 is the clone of the original and selects and deselects as it should. 框2是原始的克隆,并选择和取消选择它应该。
box 3-4 are clones of 1-2 but it seems that box 3 and 4 get the same listener because when I click on box 4 it toggles selected on box 3 and nothing happens with box 4. 方框3-4是1-2的克隆,但似乎方框3和4得到相同的监听器,因为当我点击方框4时,它在方框3上选择了切换,方框4没有任何反应。
How do I solve this? 我该如何解决这个问题?
Any help will be most welcome. 我们非常欢迎任何帮助。
I think this is a scoping issue. 我认为这是一个范围问题。 Your event handler is making reference to node
, but at the end of the loop, node
will point to the last square created. 您的事件处理程序正在引用node
,但在循环结束时, node
将指向创建的最后一个方块。 You can store the value of node
for each event handler using a closure: 您可以使用闭包为每个事件处理程序存储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);
but probably the better solution is to use this
within your event handler: 但可能更好的解决方案是在事件处理程序中使用this
:
node.addEventListener("click",function(e){
// within an event handler, 'this' references the event's target element
this.classList.toggle("selected");
console.log(e);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.