gpt4 book ai didi

javascript - 在文档内部或外部使用 jquery 就绪

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:48:26 29 4
gpt4 key购买 nike

以下两种情况给我相同的行为。但是技术上有什么区别? (我把下面的代码放在正文中脚本标签的最后一部分。)

$(document).ready(function() {
$('.collapse').collapse({toggle: false});

$(document).on('click', '#expandAllLessons', function() {
$('div.accordion-body').collapse('show');
});

$(document).on('click', '#collapseAllLessons', function() {
$('div.accordion-body.collapse').collapse('hide');
});
});

$(document).ready(function() {
$('.collapse').collapse({toggle: false});
});

$(document).on('click', '#expandAllLessons', function() {
$('div.accordion-body').collapse('show');
});
$(document).on('click', '#collapseAllLessons', function() {
$('div.accordion-body.collapse').collapse('hide');
});

谢谢。

最佳答案

或多或少,它在做同样的事情。

通过将 .on() 与子选择器一起使用,您可以使用事件委托(delegate)将任何 future 事件绑定(bind)到与该选择器匹配的任何元素。 document 是 DOM 树的最顶端(在脚本执行时可用),因此您的事件委托(delegate)有效。

.ready() 等待 DOM 组装完毕,因此您可以更可靠地使用 .click() 等方法直接绑定(bind)事件。 hover()

所以您的第一个示例只是等待 DOM 组装,然后委托(delegate)事件。第二个示例只是在脚本执行后立即委托(delegate)事件。

From jQuery's documentation regarding .on():

Direct and delegated events

The majority of browser events bubble, orpropagate, from the deepest, innermost element (the event target) inthe document where they occur all the way up to the body and thedocument element. In Internet Explorer 8 and lower, a few events suchas change and submit do not natively bubble but jQuery patches theseto bubble and create consistent cross-browser behavior.

If selector is omitted or is null, the event handler is referred to asdirect or directly-bound. The handler is called every time an eventoccurs on the selected elements, whether it occurs directly on theelement or bubbles from a descendant (inner) element.

When a selector is provided, the event handler is referred to asdelegated. The handler is not called when the event occurs directly onthe bound element, but only for descendants (inner elements) thatmatch the selector. jQuery bubbles the event from the event target upto the element where the handler is attached (i.e., innermost tooutermost element) and runs the handler for any elements along thatpath matching the selector.

关于javascript - 在文档内部或外部使用 jquery 就绪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16028771/

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