2010-05-26 28 views
1

我必须错过一些基本的东西,但是对于我的生活无法解决它。取消绑定不做它应该的

想法是当你点击那个点击事件然后解除绑定。还要注意警报('测试')没有发射。

$(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

非常感谢

回答

0

由于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(); 
} 
+0

是的那一个。非常感谢 – Dan 2010-05-26 10:03:30

0

你是你绑定后,立即解除绑定!你需要处理程序(hide)内解除绑定,以保证它的执行,否则你可能会改为考虑这个问题:

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

one将确保处理程序是只执行一次元素。

+0

那是一个很好的记忆,感谢 – Dan 2010-05-26 10:04:48