我想使用jQuery UI创建一个拖放框。我还有一个输入/提交按钮,这样每当我点击按钮时,计数就会增加。如果框被丢弃,则计数可以是1,否则它将变为0。
此代码不起作用:
$(function() {
var count = 0;
$("#draggable").draggable();
$("#droppable").droppable({
drop: function(event, ui) {
// var draggable = ui.draggable;
// alert('The square with ID "' + draggable.attr('id') + '" was dropped onto me!');
if ($(ui.draggable).hasClass("draggable")) {
$(this)
.find("p")
.html("Correct!");
count++;
$(".counttext").text("There are " + count + " divs inside parent box detail.");
if (count == 2) {
alert("You got them all right!");
}
} else {
$(this)
.find("p")
.html("Wrong!");
}
}
});
});
这里有一种方法可以完成您想要做的事情:
http://jsfiddle.net/Twisty/ttyt320c/
JQuery
var foodCount = 0;
$(function() {
$(".draggable").draggable();
$(".wrong").draggable();
$("#droppable").droppable({
accept: ".draggable",
drop: function(event, ui) {
console.log("Accepting object.");
ui.draggable.draggable("destroy");
if (ui.draggable.attr("class") === "draggable") {
foodCount++;
console.log("Count: " + foodCount);
$(".count").text(foodCount);
alert('correct');
}
}
});
});
在drop
中,我们只想接受一个特定的对象。如果需要,以后可以使用其他方式,例如恢复对象。我们检查被丢弃对象的class
。如果是draggable
,我们会更新计数并删除draggable()
功能,这样它就无法移动。