【发布时间】:2023-03-18 19:25:01
【问题描述】:
我尝试在两个 HTML 列表之间切换元素。在第一个列表中,新元素必须位于列表末尾。我使用 jQuery .appendTo() 方法添加一个元素并使用 .remove() 删除一个元素。在第二个列表中,每个元素都必须保持原位,因此我使用 .hide() 和 .show()。
这是我的 HTML 列表:
List 1
<ul id="l1"></ul>
List 2
<ul id="l2"></ul>
我的列表中的一个元素看起来像:<li>Element - <span>remove</span></li>
我向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);
});
});
问题是在将元素重新添加到第一个列表后,处理程序似乎消失了。我以与第一次相同的方式添加此元素。
为什么.click() 处理程序第二次消失了? .remove() 方法是否删除了子对象的处理程序?
【问题讨论】:
标签: javascript jquery html-lists