2

我想在第一次单击后取消绑定锚点,但是当用户单击特定按钮时,我想将单击事件重新绑定到该锚点

我写了这段代码

 $(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
    });
});

unbind功能很好,但是bind功能不行,为什么?以及如何使其工作?

4

3 回答 3

4

将您的点击功能存储在一个变量中,以便可以轻松地重新分配它......

$(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
  });    
});
于 2011-07-07T20:05:52.540 回答
0

你必须传递一个回调来绑定,一旦它解除绑定它就不会记住任何东西。这意味着当您在 #activate.click 中再次指定绑定时,您必须在那里指定函数。可能最好的方法是在其他地方指定函数并将其用于绑定调用。在下面的示例中,我使用 jquerys .data 在“clickFunc”下存储一个函数,然后将其用作 .click 的回调。您也可以使用 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/

于 2011-07-07T20:02:00.863 回答
0

尝试将第一个绑定更改为.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>);
    });
于 2011-07-07T20:02:31.310 回答