[英]Children handlers disappeared after removing and readding element
I try to switch elements between two HTML lists. 我尝试在两个HTML列表之间切换元素。 In the first list, a new element must be at the end of the list.
在第一个列表中,新元素必须位于列表的末尾。 I use the jQuery
.appendTo()
method to add an element and .remove()
to remove an element. 我使用jQuery
.appendTo()
方法添加元素,并使用.remove()
删除元素。 In the second list every elements must stay in place so I use .hide()
and .show()
. 在第二个列表中的每个元素都必须留在地方,所以我用
.hide()
和.show()
Here is my HTML lists : 这是我的HTML列表:
List 1
<ul id="l1"></ul>
List 2
<ul id="l2"></ul>
An element of one of my lists looks like : <li>Element - <span>remove</span></li>
我的列表之一的元素看起来像:
<li>Element - <span>remove</span></li>
I add an handler to the span
to remove the element from the list and add it in the other list. 我向
span
添加了一个处理程序,以从列表中删除该元素,并将其添加到另一个列表中。
let ul1 = $("ul#l1"),
ul2 = $("ul#l2"),
lis = ["ga", "bu", "zo", "meu"];
lis.forEach(function(e){
let li1 = $("<li>" + e + "- </li>"),
sp1 = $("<span>remove</span>"),
li2 = $("<li>" + e + "- </li>"),
sp2 = $("<span>hide</span>");
sp1.appendTo(li1);
li1.appendTo(ul1);
sp2.appendTo(li2);
li2.appendTo(ul2);
li2.hide();
// switching the element from the list 1 to the list 2
sp1.on("click", function(){
li2.show();
li1.remove();
});
// switching the element from the list 2 to the list 1
sp2.click(function(){
li2.hide();
li1.appendTo(ul1);
});
});
The problem is that after re-adding the element to the first list, the handler seems to have disappeared. 问题在于,将元素重新添加到第一个列表后,处理程序似乎已经消失了。 I add this element the same way as the first time.
我以与第一次相同的方式添加此元素。
Why has the .click()
handler disappeared the second time ? 为什么
.click()
处理函数第二次消失了? Is the .remove()
method removing children object's handlers? .remove()
方法是否删除子对象的处理程序?
As per jquery doc 根据jQuery文档
https://api.jquery.com/remove/ https://api.jquery.com/remove/
all bound events and jQuery data associated with the elements are removed.
与元素关联的所有绑定事件和jQuery数据都将被删除。 To remove the elements without removing data and events, use .detach() instead.
要删除元素而不删除数据和事件,请改用.detach()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.