【问题标题】:How to clone an element with jQuery?如何使用 jQuery 克隆元素?
【发布时间】:2017-11-11 11:20:44
【问题描述】:

我正在尝试使用 jQuery 实现拖放功能,效果很好,现在我想用旧位置的另一个元素替换拖动的元素。

我正在使用clone() 方法,但由于我是 jQuery 新手,我编写的代码会无限克隆元素,有人可以帮助我吗?

这是我的代码:

<script> 
$(function() {
    $(".draggable").draggable(
        {
            drag : function(event, ui) {
                $(this).clone().appendTo(this)
            }
        });

    $(".droppable").droppable({
        drop: function(event, ui) {
            $(this).addClass("ui-state-highlight")
        }
    });
});
</script>

【问题讨论】:

标签: jquery clone jquery-ui-draggable


【解决方案1】:

这基本上有效。但是您必须根据需要对其进行调整。

var dropclone;
$( ".draggable" ).draggable({
    start: function (event, ui) {
        dropclone = ui.helper.clone();
    }
});
$( ".droppable" ).droppable({
    drop: function() {
        $('body').append(dropclone);
    }
});

【讨论】: