无法将li元素从一个无序列表移动到另一个列表

4
我有两个无序列表。
<ul id="#list1">
<li>one</li>
<li>two</li>
</ul>

<ul id="#list2"></ul>

以及两个按钮

<input id="add" name="yt1" type="button" value="<<" /><br />
<input id="remove" name="yt2" type="button" value=">>" /> 

如果按下id为add的按钮,则应将来自#list1的所有元素移动到#list2。如何使用JQuery将元素从一个列表移动到另一个列表?
我想到了以下内容,但不确定如何实际移动。
$("#add").click(function(){
$("#list1 li").each(function(){
//Do not know what to put in here
}
})
4个回答

10
你可以使用appendTo
$("#add").click(function(){
    $("#list1 li").appendTo('#list2');
});

演示

同时将您的ID从<ul id="#list1">更改为<ul id="list1">


+1 - 我不知怎么会想到.appendTo不会移除匹配的元素。 - karim79

1
      $('#list2').html( $('#list1').html() );

1
绑定到列表元素的任何事件处理程序都将丢失。 - Felix Kling

1
  //this will move selected items from yt1-list to yt2-list     
  $("#yt1 option:selected").appendTo("#yt2");

  //this will move all selected items from yt1-list to yt2-list
  $("#yt1 option").appendTo("#yt2");

0

试试这个。虽然我没有测试过它,但它应该可以(逻辑上讲)。

$("#add").click(function(){
$("#list1 li").each(function(){
var holder;
$(this) = holder;
$(this).remove();
$('#list2').append();
}
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接