微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何让JQuery事件为2个类工作?

<script>
$(function(){
    $('.logger').bind('click',function(){
        alert('we will log that the user shared something');
        return true; //keep going,pretend nothing happened.
    });

    $('.share').bind('click',function(){
        window.open('blah');
        return false; 
    });
});
</script>
<a href="#" class="share logger">Share this</a>

我希望能够触发记录器和共享功能.但是现在,只触发了共享功能.如果我评论共享功能,那么记录器功能正常.

我也尝试改变“类”,以便记录器在分享之前.

解决方法

当你返回false时;在停止事件传播的事件处理程序中,这就是未触发其他处理程序的原因.如果您只想停止认操作,请使用event.preventDefault().

这个article很好地解释了这个概念:

First off,return false is actually
doing three very separate things when
you call it:

  1. event.preventDefault();
  2. event.stopPropagation();
  3. Stops callback execution and returns
    immediately when called.

“Wait a
minute,” you cry! I only needed to
stop the default behavior! I don’t
need these other two items
… I think.

The only one of those three actions
needed to cancel the default behavior
is preventDefault(). Unless you mean to actually stop event propagation (bubbling),using return false will greatly increase the brittleness of your code

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐