多次丢弃事件后的警报触发器

时间:2012-10-16 11:06:55

标签: jquery jquery-droppable jquery-draggable

我必须承认,我几乎是一个菜鸟,但我一直在努力解决这个问题。在两次丢弃都发生后我必须触发if,现在它在加载时触发。我在那里错过了什么?

$(function() {
    $( "#draggable" ).draggable({
        revert: "invalid",
        snap: "#droppable",
    });
    $( "#droppable" ).droppable({
        accept: "#draggable",
        drop: function() {
            $("#whistle").get(0).play();
            $(this).data(droppable)
        }
    });
    $( "#draggable2" ).draggable({
        revert: "invalid",
        snap: "#droppable",
    });
    $( "#droppable2" ).droppable({
        accept: "#draggable2",
        drop: function() {
            $("#whistle").get(0).play();
            $(this).data(droppable2)
        }
    });
    if ($.queue(2)) {
        $("#whistle2").get(0).play();
        alert ("done!")
    }
});

1 个答案:

答案 0 :(得分:0)

您可以使用两个$.Deferred及其promise - 对象来触发您的处理程序:

$(function() {

    var dfd1 = $.Deferred();
    var dfd2 = $.Deferred();

    $( "#draggable" ).draggable({
        revert: "invalid",
        snap: "#droppable",
    });
    $( "#droppable" ).droppable({
        accept: "#draggable",
        drop: function() {
            $("#whistle").get(0).play();
            $(this).data(droppable);
            dfd1.resolve();
        }
    });
    $( "#draggable2" ).draggable({
        revert: "invalid",
        snap: "#droppable",
    });
    $( "#droppable2" ).droppable({
        accept: "#draggable2",
        drop: function() {
            $("#whistle").get(0).play();
            $(this).data(droppable2);
            dfd2.resolve();
        }
    });
    //this will trigger when both dfds have been resolved
    $.when(dfd1.promise(), dfd2.promise()).then(function(){
        $("#whistle2").get(0).play();
        alert ("done!")
    });
});

请参阅this fiddle进行演示(点击两个按钮,看看神奇的事情!)并阅读$.Deferred$.when