解除绑定不做应该做的事

发布于 2024-09-02 14:49:05 字数 395 浏览 5 评论 0原文

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

这个想法是当您单击时,单击事件就会解除绑定。另请注意,警报('测试')未触发。

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

非常感谢

I must be missing something fundamental, but for the life of me cant work it out.

the idea is when u click that click event is then unbind. Also to note the alert('test') is not firing.

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

Using jquery 1.4

Many Thanks

Dan

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

给妤﹃绝世温柔 2024-09-09 14:49:05

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

Since jQuery supports a fluent programming style bind actually returns the this object.

So in this case you are first adding the handler and then immediately removing it.

The correct version is

$(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();
} 
岁月无声 2024-09-09 14:49:05

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

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

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

You are unbinding immediately after you bind! You'll need to unbind within the handler (hide) to ensure that it's executed, otherwise you might consider this instead:

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

one will ensure that a handler is only executed once per element.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文