动态添加元素上的jQuery UI droppable吗? [英] jQuery UI droppable on dynamically added element?
问题描述
在将jQueryUI droppable应用于动态创建的div时遇到问题.
I'm having a problem with applying jQueryUI droppable to a dynamically created div.
$(".item").draggable({ helper: 'clone'});
$(".box").draggable({containment : '#area'});
$(".box").droppable({
drop: function(event, ui) {
if ($(ui.draggable).hasClass("area")){
// call another function
}else{
$(this).append($(ui.draggable).clone().removeClass('item').addClass('area'));
$('.area').draggable();
}
}
});
应该将.item
放入.box
.直到我调用第二个功能(通过单击按钮),它才能正常工作:
An .item
is supposed to drop in .box
. It works well until I call the second function (by clicking a button):
function add_box(){
$("<div class='box'></div>").prependTo( "#area" );
$(".box").droppable(); // i tried this (didn't work).
$(".box").draggable(); // should be draggable as well
}
推荐答案
在 add_box 函数中调用$(".box").droppable();
时,您将可拖放重新应用于所有 .box 项,但没有选项,因此您将失去预期的行为.
When you're calling $(".box").droppable();
in add_box function, you're reapplying droppable to all .box items, but without the options, so you're losing your expected behavior.
您应该仅将其应用于新创建的元素,并且还需要定义选项.例如,您可以执行以下操作:
You should apply it only to the newly created element, and you need to define your options as well. You could do something like this for example:
// define your options as an object
var droppableOptions = {
drop: function(event, ui) {
if ($(ui.draggable).hasClass("area")){
// call another function
} else {
$(this).append($(ui.draggable).clone().removeClass('item').addClass('area'));
$('.area').draggable();
}
}
}
function add_box(){
var newBox = $("<div class='box'></div>").prependTo( "#area" );
// you apply droppable to your new box, with the options you need
newBox.droppable(droppableOptions);
newBox.draggable(); // should be draggable as well
}
这篇关于动态添加元素上的jQuery UI droppable吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!