简体   繁体   中英

Why jQuery appendTo removes the existing list item?

I am working on a project in which I need to add the list items from list1 to list2 on dblclick of it or either pressing Add button. So far I have accomplished this Working jsfiddle .

 $().ready(function() {  
var classHighlight = 'highlight';
var $thumbs = $('ul li').click(function(e) {
    e.preventDefault();
    $thumbs.removeClass(classHighlight);
    $(this).addClass(classHighlight);
});
$('#select1').on ("dblclick","li", function(){
return $(this).appendTo('#select2').removeClass('highlight'); 
});
$('#select2').on ("dblclick","li", function(){
return $(this).remove(); 
});
   $('#add').click(function() {  
   $('#select1 .highlight').appendTo('#select2').removeClass('highlight'); 
   });  
   $('#remove').click(function() {  
     $('#select2 .highlight').remove();
   });  
  });  

But if you see clicking on the list1 item also removes the clicked item from list1 which I dont want to. I only need to copy it from list1 to list2 Can anyone help me with this? Thank You

When you append an existing element to a new parent, you move it; it doesn't get copied. You should clone the element first and then append cloned element:

$('#select1').on ("dblclick","li", function(){
  return $(this).clone().appendTo('#select2').removeClass('highlight'); 
});

and

$('#add').click(function() {  
 $('#select1 .highlight').clone().appendTo('#select2').removeClass('highlight'); 
});   

Working Demo

you use clone() function to help in this code

$('#select1').on ("dblclick","li", function(){
   return $(this).clone().appendTo('#select2').removeClass('highlight'); 
});

whole code here http://jsfiddle.net/s41txkng/4/

https://api.jquery.com/clone/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM