jquery catch delayed each is finished?

2019-09-15 18:55发布

$("#div_game_container").on("click", ".square", squareClick);

function squareClick() {
    var group = $(this).data("group");

    if ($("." + group).hasClass("active")) {

        // off click event
        $("#div_game_container").off("click", ".square", squareClick);

        $("." + group).each(function (index) {
            $(this).delay(100 * index).fadeOut(100);
        });

        // on click event. this line does not wait "each" function 
        $("#div_game_container").on("click", ".square", squareClick);
}

above code does not work. Actually, it works but not my expected. I commented out what is the problem.

Also I add the delay like this:

$("#div_game_container").delay(each_delay_time).on("click", ".square", squareClick);

but there is no change. How can I catch that "each" iteration is finished? I want to prevent click event, while each method is running, and after each method finished, then active click event

1条回答
smile是对你的礼貌
2楼-- · 2019-09-15 19:09

Use the .promise() object:

$("." + group).each(function (index) {
    $(this).delay(100 * index).fadeOut(100);
});
$("." + group).promise().done(function() {
    $("#div_game_container").on("click", ".square", squareClick);
});
查看更多
登录 后发表回答