javascript 将 li 从一个 ul 移动到另一个 jQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18541415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
moving li from one ul to another jQuery
提问by i_me_mine
I'm trying to move list items from one un-ordered list to another. This works fine the first time but once the items are moved I am unable to move them back. I made a fiddle to illustrate what i'm talking about.
我正在尝试将列表项从一个无序列表移动到另一个列表。这第一次工作正常,但是一旦物品被移动,我就无法将它们移回。我做了一个小提琴来说明我在说什么。
Check it out here -> jsfiddle
在这里查看-> jsfiddle
HTML
HTML
<table>
<tr>
<td>Numbers</td>
<td>Letters</td>
</tr>
<tr>
<td>
<ul class='list1'>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</td>
<td>
<ul class='list2'>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
<li>e</li>
</ul>
</td>
</tr>
</table>
<input type='button' value='<<' id='move_left' />
<input type='button' value='>>' id='move_right' />
jQuery
jQuery
$('body').on('click', 'li', function() {
$(this).toggleClass('selected');
});
$('#move_left').click(function() {
$('.list1').append('<li>', $('.list2 .selected').text(), '</li>');
$('.list2 .selected').remove();
});
$('#move_right').click(function() {
$('.list2').append('<li>', $('.list1 .selected').text(), '</li>');
$('.list1 .selected').remove();
});
CSS
CSS
ul {
list-style-type:none;
padding:0px;
margin:0px;
}
.selected {
background-color:#efefef;
}
As you can see the items move from left to right or right to left, yet once they are moved i am unable to move them back. Any help is appreciated.
如您所见,这些项目从左到右或从右到左移动,但是一旦它们被移动,我就无法将它们移回。任何帮助表示赞赏。
回答by bfavaretto
It's easier than you think:
这比你想象的要容易:
$('#move_left').click(function() {
$('.list1').append($('.list2 .selected').removeClass('selected'));
});
$('#move_right').click(function() {
$('.list2').append($('.list1 .selected').removeClass('selected'));
});
When you append an existing element to another, it is moved there. No need to clone the elements and manually remove the originals as you were doing.
当您将现有元素附加到另一个元素时,它会移动到那里。无需像您一样克隆元素并手动删除原始元素。
回答by Liam Allan
try:
尝试:
$('#move_left').click(function() {
$('.list2 .selected').each(function(){
$('.list1').append('<li>'+$(this).text()+'</li>');
});
$('.list2 .selected').remove();
});
$('#move_right').click(function() {
$('.list1 .selected').each(function(){
$('.list2').append('<li>'+$(this).text()+'</li>');
});
$('.list1 .selected').remove();
});