简体   繁体   中英

Clone elements in DOM with 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 .

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');
});

将$('。addd-body')。click(...)更改为$('。addd-body> a')。click(...)似乎您有一个附加到LI元素的处理程序,然后传播到锚元素并再次运行。

Try like this:

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

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