Clonar elementos en DOM con jQuery

I need to clone an element from the DOM to make it fly to a basket. I'm using .clone() from jQuery. The problem is when I first click the element, it clones twice instead of once, and when I click it again it clones once. Why does this happen?

My piece of code:

$(document).ready(function() {
$('.addd-body').click(function() {
    $(this).parent().clone().prependTo('.carro');
});});

You can see the working code on Mashini website.

preguntado el 08 de noviembre de 11 a las 18:11

3 Respuestas

Please update when you figure out the cause; I think there is more to it since your code looks fine.

Test1: try changing your code to stop propagation

$('.addd-body').click(function(e) {
    $(this).parent().clone().prependTo('.carro');
    e.stopPropagation();
});

Test2: try scoping your click events down to the actual link

$('.addd-body').delegate('click', 'a.item_add', function() {
    $(this).closest('ul').clone().prependTo('.carro');
});

respondido 08 nov., 11:23

Change $('.addd-body').click(...) to $('.addd-body > a').click(...) It seems that you have a handler attached to the LI element that then propagates to the anchoe elements and runs once more.

respondido 08 nov., 11:22

thnkz, that works, i added that and a .parent() to get the entire row $(document).ready(function() { $('.addd-body > a').click(function() { $(this).parent().parent().clone().prependTo('.carro'); }); }); - Joako Parra

Yeah, forgot about the parent() stuff, sorry) - Caramelos Gratis

Intente así:

$(document).ready(function() {
$('.item_add').click(function() {
    $(this).parents(".body-cart:first").clone().prependTo('.carro');
});});

respondido 08 nov., 11:22

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.