jQuery remove an object and replace in same spot
How would I go about removing an object say from an unordered list and add it to another list while keeping开发者_开发技巧 its location? I know i can set the original item to hide() but then that leaves a small space where the item use to appear. Say i have a list A and B, if a user clicks on an item in A it needs to be added to B and removed from A. If they now click on a button to remove it from B and back to A, i want to have it displayed in the same spot it originally did. I know i can add it via append() but that won't put it in the same location. Thoughts anyone?
You could use .clone? so:
<ul id="firstlist">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
<ul id="secondlist">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
the jquery:
var object = $('#firstlist > li :last ').clone();
$('#secondlist').append(object);
$('#firstlist > li :last ').destroy();
Obviously you can swap this round to add it to the first list, but to get the position you could use a number of ways, I would probably do:
$('#firstlist').children('li').each(function(i){
});
and use "i" to get the position. you can append after a given object to so:
$('#firstlist').children('li').each(function(i)
{ if(i== 4){ $(this).append(object).after(this) }
Heres my bid:
- Allows you to click an element in list-1 and it will hide that instance, and append a clone to list-2.
- Clicking the item in list-2 will return it back to list-1, in the same position it came from.
- Clicking "original elements" in list-2 will not copy over to list-1.
HTML:
<ul id="list-1">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
<ul id="list-2"></ul>
JavaScript:
var $list1 = $('#list-1');
var $list2 = $('#list-2');
$list1.children('li').each(function(i,e){
var ulId = $(this).closest('ul').attr('id');
$(this).attr('li-id',ulId+'_'+i);
}).click(function(e){
if ($list2.find('li[li-id="'+$(this).attr('li-id')+'"]').length == 0){
var liClone = $(this).clone();
liClone.click(function(e){
var elId = $(this).attr('li-id');
$list1.find('li[li-id="'+elId+'"]').show();
$(this).remove();
});
$list2.append(liClone);
}
$(this).hide();
});
Fiddle: http://www.jsfiddle.net/vgx23/1/
精彩评论