【问题标题】:Unbind not doing what it should解绑不做应该做的事
【发布时间】:2011-02-24 02:25:18
【问题描述】:

我一定错过了一些基本的东西,但我这辈子都无法解决。

这个想法是当你点击那个点击事件然后解除绑定。还要注意 alert('test') 没有触发。

  $(document).ready(function() {
  $('#menu .cat-item a').each( function() {
    $(this).bind('click',hide).unbind('click',hide);
  });
 });


 function hide(){
   alert('test')
    $("#home-content").fadeIn();
   $("#home-page").fadeOut();
 } 

使用 jquery 1.4

非常感谢

【问题讨论】:

    标签: javascript unbind jquery-1.4


    【解决方案1】:

    由于 jQuery 支持流畅的编程风格,bind 实际上返回了this 对象。

    所以在这种情况下,您首先添加处理程序,然后立即删除它。

    正确的版本是

    $(document).ready(function() {
        $('#menu .cat-item a').each( function() {
             $(this).bind('click',hide);
        });
    });
    
    
    function hide(){
        $(this).unbind('click',hide);
        $("#home-content").fadeIn();
        $("#home-page").fadeOut();
    } 
    

    【讨论】:

    • 是的,就是这样。非常感谢
    【解决方案2】:

    绑定后立即解除绑定!您需要在处理程序 (hide) 中取消绑定以确保它被执行,否则您可能会考虑这样做:

    $(document).ready(function() {
        $('#menu .cat-item a').one("click", hide);
    });
    

    one 将确保每个元素只执行处理程序一次

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-28
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      相关资源
      最近更新 更多