【问题标题】:Why does draggable not work for dynamically created elements?为什么可拖动对动态创建的元素不起作用?
【发布时间】:2019-03-23 11:18:32
【问题描述】:
我的可拖动元素是动态创建的。每次我添加一个项目时,我都会再次调用 draggable() 。他们得到可拖动的类,但不要拖动。
在将可拖动元素写入调试控制台时,它成功地适用于非动态元素。
$(window).on('load', function () {
var item = '<div class="item"></div>';
$field.append(item);
dragItems();
});
function dragItems() {
var $items = $('.item');
$items.draggable();
}
在检查器中,我看到创建了拖动类,但没有发生移动。
【问题讨论】:
标签:
javascript
jquery-ui
draggable
【解决方案1】:
考虑以下示例。
$(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 一起使用。
希望对您有所帮助。