gpt4 book ai didi

javascript - $(document).ready 和编写打开的 jQuery 语句之间的区别

转载 作者:行者123 更新时间:2023-11-29 16:16:02 26 4
gpt4 key购买 nike

编写代码时使用和不使用$(document).ready有什么区别?

例如:

$(document).ready(function() {
$("#button").click(function() {
//Code
});
});

和:

$("#button").click(function() {
//Code
});

和:

 <input id="button" type="button" value="Cancel" onclick="hidedropdown()" />

function hidedropdown() {
//Code
}

最佳答案

在第一种情况下,直到 DOM 准备好后才执行代码。

参见 documentation :

The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.

如果你执行 script 中的第二个代码位于 HTML 开头或 header 中的元素 button不会找到元素,也不会绑定(bind)任何事件处理程序。使用 .ready解决这个问题。

将脚本放在页面底部(与 </body> 相邻)也可以解决这个问题,原因相同 - 在解析脚本时,HTML 将转换为 DOM,您可以遍历它。

关于javascript - $(document).ready 和编写打开的 jQuery 语句之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15702760/

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