Unbind / off clicked事件在jQuery中不起作用?

时间:2014-02-28 06:55:24

标签: jquery unbind

我使用jquery(1.10)取消绑定点击的事件:

function fnDoVoteContent() {
    var btnUpvote = ".btn-upvoting";
    var btnDownVote = ".btn-downvoting";

    $(document).on('click', btnUpvote, function(){
        vote(param1, param2, param3);
    });


    $(document).on('click', btnDownVote, function(){
        vote(param1, param2, param3);
    });
}

function vote(param1, param2, param3) {

    $.ajax({
        url: votingUrl,
        cache: false,
        type: "POST",
        dataType: "json",
        beforeSend: function(){
            //do business logic
           $("a").off( "click" ); // Line 1: Unbind clicked events

        },
        complete: function(){
            //do business logic
           $("a").on( "click" ); // Line 2: re-bind again

        },
        success: function(data) {
            //update data
        }
    });
}

业务逻辑代码有效,但Line 1 and 2的代码无效。难道我做错了什么?

1 个答案:

答案 0 :(得分:1)

这根本不是它的运作方式?你必须绑定和取消绑定到同一个选择器,你必须再次重新绑定到一个函数,只是做$('a').on('click')什么都不做。

为此,您可以使用命名空间事件

function fnDoVoteContent() {
    var btnUpvote = ".btn-upvoting";
    var btnDownVote = ".btn-downvoting";

    // bind event handlers
    $(document).on('click.custom', btnUpvote, function(){
        vote(param1, param2, param3);
    });

    $(document).on('click.custom', btnDownVote, function(){
        vote(param1, param2, param3);
    });
}

function vote(param1, param2, param3) {

    $.ajax({
        url: votingUrl,
        cache: false,
        type: "POST",
        dataType: "json",
        beforeSend: function(){
            //do business logic

            // unbind has to be done on the same selector
            $(document).off('click.custom');

        },
        complete: function(){
            //do business logic
            $(document).on('click.custom', btnUpvote, function(){
                vote(param1, param2, param3);
            });

            $(document).on('click.custom', btnDownVote, function(){
                vote(param1, param2, param3);
            });

        },
        success: function(data) {
            //update data
        }
    });
}