jQuery stopPropagation 气泡向下
我有一个 div,里面有一个链接:
<div id="myDiv">
<a href="http://www.lol.com">Lol</a>
</div>
单击
I have a div with a link inside of it:
<div id="myDiv">
<a href="http://www.lol.com">Lol</a>
</div>
Clicking the <div />
should go somewhere, but clicking the child <a />
should go to www.lol.com. I've seen from previous questions and the jQuery website that .stopPropagation prevents bubbling upwards, but how do I prevent a bubble downwards (isn't that what's necessary here?).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事件只会冒泡。因此,
a
元素的单击事件处理程序在div
的单击事件处理程序之前触发。如果您想要您描述的行为,则需要向 a 元素添加一个单击事件处理程序,以停止传播到 div。并将您拥有的任何事件处理程序保留在 div 上。这应该允许事件执行其默认操作,并防止 div 上的处理程序被触发。
如果您只想阻止点击链接,那么您可以更改
div
元素的事件处理程序Events only bubble up. So the click event handler for the
a
element is fired before the click event handler for thediv
. If you want the behaviour you describe, the you need to add a click event handler to the a element which stops propagation to the div.and keep whatever event handler you have on the div. This should allow the event to perform it's default action, and prevent the handler on the div being fired.
If you only want to prevent clicks on links then you can change your event handler for the
div
element问题是单击锚点仍然会触发
中的单击。这就是所谓的“事件冒泡”。
事实上,有多种解决方案:
在 DIV 单击事件处理程序中检查实际目标元素是否是锚点
→ jsFiddle
停止锚点点击侦听器的事件传播 → jsFiddle
正如您可能已经注意到的,我从示例中删除了以下选择器部分:
这是不必要的,因为没有 .expandable- 类的元素panel-heading 也以
#ancherComplaint
作为其 ID。我假设您想抑制锚点的事件。这不能以这种方式工作,因为两个选择器(你的和我的)选择完全相同的 DIV。选择器被调用时对监听器没有影响;它仅设置侦听器应注册到的元素列表。由于这个列表在两个版本中都是相同的,因此不存在差异。
The problem was that clicking the anchor still triggered a click in your
<div>
. That's called "event bubbling".In fact, there are multiple solutions:
Checking in the DIV click event handler whether the actual target element was the anchor
→ jsFiddle
Stopping the event propagation from the anchor click listener → jsFiddle
As you may have noticed, I have removed the following selector part from my examples:
This was unnecessary because there is no element with the class .expandable-panel-heading which also have
#ancherComplaint
as its ID.I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.