javascript - 如何使 JQuery 事件适用于 2 个类?

标签 javascript jquery html css

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

我希望能够同时触发记录器和共享功能。但是现在,只有分享功能被触发。如果我评论共享功能,那么记录器功能就可以正常工作。

我还尝试更改“类”,以便记录器在共享之前。

最佳答案

当您在停止事件传播的事件处理程序中 return 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

关于javascript - 如何使 JQuery 事件适用于 2 个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6620776/

相关文章:

javascript - 视频修改 javascript、HTML、CSS

javascript - 如何使用 id 上匹配的另一个 2D 数组更新 2D 数组

javascript - 通过点击获取div id

jquery - Excanvas 可以在 IE 8 中工作吗?

JavaScript Promise - 如何做出多重 promise ?

javascript - 如何在ajax之外访问dataTable变量

javascript - 如何使用javascript获取按钮的选定值

javascript - 浏览器自动添加 <a>-标签,无需 JavaScript

java - 如何删除 Jsoup 中的 HTML 实体?

html - YouTube 上传小部件是否使用 Flash 或 HTML5