繁体   English   中英

为什么draggable 不适用于动态创建的元素?

[英]Why does draggable not work for dynamically created elements?

我的可拖动元素是动态创建的。 每次添加项目时,我都会再次调用draggable()。 他们得到可拖动的类,但不要拖动。

将 draggable 写入调试控制台时,它成功地与非动态元素一起使用。

$(window).on('load', function () {
    var item = '<div class="item"></div>';
    $field.append(item);
    dragItems();

});

function dragItems() {
    var $items = $('.item');

    $items.draggable();

}

在检查器中,我看到创建了拖动类,但没有发生移动。

考虑以下示例。

 $(function() { function dragItems(dObj) { dObj.draggable({ containment: "parent" }); } var item = '<div class="item"></div>'; $("#field").append(item); dragItems($("#field .item")); });
 #field { width: 400px; height: 200px; background: #CFC; } .item { width: 100px; height: 100px; background: #CCC; }
 <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div id="field"></div>

我怀疑您的示例中有更多代码。 这被包裹在$(function(){}); 这将等到document ready 类似于$(window).on('load')

该函数设置为接受 jQuery 对象并将 Draggable 分配给该对象。 因此,您必须将$("#field .item")对象传递给它。

现在,如果您先创建了对象,则代码可能会少一些。 您当前的代码不是创建对象,而是通过附加注入 HTML 字符串。 考虑以下。

 $(function() { function dragItems() { $("#field .item").draggable({ containment: "parent" }); } var item = $("<div>", { class: "item" }); $("#field").append(item); dragItems(); });
 #field { width: 400px; height: 200px; background: #CFC; } .item { width: 100px; height: 100px; background: #CCC; }
 <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div id="field"></div>

我认为,这更像是您想要做的,您只需将所有.item元素设置为可拖动。 您可以使用任一方法。 我只是确保您以一种或另一种方式创建一个对象以与 Dragable 一起使用。

希望有帮助。

暂无
暂无

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

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