how to rebind click event to anchor after unbind?

2019-07-13 02:20发布

I want to unbind the anchor after the first click, but when user click a specific button, I want to rebind the click event to this anchor

I wrote this code

 $(document).ready(function(){
    $("a.package").click(function(){
        //alert('click');            
        $(this).unbind('click'); 
        // the rest of the code
    });

    $('#activate').click(function(){
        $('a.package').bind('click');
        // the rest of the code
    });
});

the unbind function works well, but the bind function does not work, why? and how to make it work?

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-13 02:50

You have to pass a callback to bind, it doesn't remember anything once it is unbound. Meaning when you specified the bind again in the #activate.click you would have to specify the function there. Probably the best way to do this is specifiy the function else where and use that for the bind call. In the example below i use jquerys .data to store a function under 'clickFunc' and then use this as the callback for the .click . You could just also use a var.

$(document).ready(function(){
    $("#package").data('clickFunc', function () {
        alert("Click");
        $(this).unbind('click');
    })
    console.log($('#package').oclick);
    $("#package").click($('#package').data('clickFunc'));

    $('#activate').click(function(){
        $("#package").click($('#package').data('clickFunc'));
        // the rest of the code
    });
});

http://jsfiddle.net/nj65w/13/

查看更多
虎瘦雄心在
3楼-- · 2019-07-13 02:56

Store your click function in a variable so that it can easily be re-assigned...

$(document).ready(function() {
  var onclick = function(e) {
    //alert('click');            
    $(this).unbind('click'); 
    // the rest of the code
  }

  $("a.package").click(onclick);

  $('#activate').click(function() {
    $('a.package').click(onclick);
    // the rest of the code
  });    
});
查看更多
倾城 Initia
4楼-- · 2019-07-13 02:57

Try changing the first binding to .one().

$("a.package").one("click", function(){
            // alert('click');            
            // $(this).unbind('click'); <-- no need, using .one
            // call your "when clicked" function
        });
$('#activate').click(function(){
        $('a.package').click(<your "when clicked" function>);
    });
查看更多
登录 后发表回答