gpt4 book ai didi

jquery - jQuery 中的事件冒泡

转载 作者:行者123 更新时间:2023-12-01 06:48:40 26 4
gpt4 key购买 nike

我不确定应该如何解决 jQuery 中的以下事件冒泡情况。

我在列表元素 (li) 中有一个链接,它有一个单击事件。我想在 li 元素上放置一个操作,如果用户单击列表元素内的链接,它将调用链接事件(单击)并调用 li 上的操作(当单击 li 或其中的任何内容时,我总是想触发 li 上的单击事件)。

我应该如何实现这个目标?

这是 HTML 代码:

<li>
<img src="images/img.png" />
<a href="/remote/path" data-remote="true">Link</a>
</li>

和 jQuery 代码(显然不起作用):

$("li a").click(function(e) {
e.preventBubble = true;
});

$("li").click(function() {
$el = $(this).find('a');
$el.click();
$(this).addClass('active');
});

对此最优雅的解决方案是什么?

感谢您的帮助!

最佳答案

如果我理解正确,你应该使用 jQuery .stopPropagation()而不是自己实现。

event.stopPropagation()

Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

以及实现:

$("li a").click(function(e) {
e.stopPropagation();
});

关于jquery - jQuery 中的事件冒泡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18547029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com