简体   繁体   English

使用jQuery克隆DOM中的元素

[英]Clone elements in DOM with jQuery

I need to clone an element from the DOM to make it fly to a basket. 我需要从DOM中克隆一个元素,以使其飞向篮子。 I'm using .clone() from jQuery. 我正在使用jQuery的.clone() 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 . 您可以在Mashini网站上查看工作代码。

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 Test1:尝试更改您的代码以停止传播

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

Test2: try scoping your click events down to the actual link Test2:尝试将点击事件的范围缩小到实际链接

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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