gpt4 book ai didi

jquery - 返回 false 不应该阻止 jQuery on() 冒泡吗?

转载 作者:行者123 更新时间:2023-12-01 02:03:49 26 4
gpt4 key购买 nike

根据the jQuery docs

Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault(). A false value can also be passed for the handler as a shorthand for function(){ return false; }. So, $("a.disabled").on("click", false); attaches an event handler to all links with class "disabled" that prevents them from being followed when they are clicked and also stops the event from bubbling.

所以当我创建点击事件时:

$('#sidebar').on("click", ".toggle", function() {
$(this).parents("p").next("ul").toggle(400);
return false;
});

我希望点击不会注册,因为它没有机会从 .toggle 传播到 #sidebar

我想到的唯一解释是,如果允许这种情况发生,就会使 on() 函数变得毫无意义,所以在这种情况下它可能会被绕过?

就冒泡而言,on() 遵循什么规则?

最佳答案

实际上,处理程序附加到元素 #sidebar,而不是 .toggle 元素。

因此,当您单击内部元素时,事件会冒泡,直到到达“#sidebar”,然后仅执行处理程序。在处理程序中返回 false,然后将停止进一步向上的传播。

<小时/>

.on() 的文档通过一个例子提到了这一点:

In addition to their ability to handle events on descendant elements not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody, this example attaches a handler to 1,000 elements:

$("#dataTable tbody tr").on("click", function(event){
alert($(this).text());
});

A delegated-events approach attaches an event handler to only one element, the tbody, and the event only needs to bubble up one level (from the clicked tr to tbody):

$("#dataTable tbody").on("click", "tr", function(event){
alert($(this).text());
});

关于jquery - 返回 false 不应该阻止 jQuery on() 冒泡吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8648539/

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