簡體   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