[英]How do I make JQuery event work for 2 classes?
<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>
I want to be able to trigger BOTH the logger and the share functions.我希望能够同时触发记录器和共享功能。 But right now, only the share function is triggered.
但是现在,只有共享 function 被触发。 If I comment share function, then the logger function works fine.
如果我评论分享 function,那么记录器 function 工作正常。
I've also tried to change the "class" so that logger is before share.我还尝试更改“类”,以便记录器在共享之前。
When you return false;
当你
return false;
in an event handler that stops the event propagation, that is why the other handler is not triggered.在停止事件传播的事件处理程序中,这就是不触发另一个处理程序的原因。 If you just want to stop the default action, use
event.preventDefault()
.如果您只想停止默认操作,请使用
event.preventDefault()
。
This article does a good job explaining the concept:这篇文章很好地解释了这个概念:
First off, return false is actually doing three very separate things when you call it:
首先,当你调用它时,return false 实际上是在做三件非常不同的事情:
- event.preventDefault();
event.preventDefault();
- event.stopPropagation();
event.stopPropagation();
- 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() .
取消默认行为所需的这三个操作中唯一的一个是preventDefault() 。 Unless you mean to actually stop event propagation (bubbling), using return false will greatly increase the brittleness of your code
除非您打算真正停止事件传播(冒泡),否则使用 return false 会大大增加代码的脆弱性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.