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

标签 javascript jquery

编写代码时使用和不使用$(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/

相关文章:

javascript - 在可滚动区域内但在内部 div 之上创建嵌入阴影

jquery - 将鼠标悬停在图像上作为链接的问题

php - 403 禁止从 ajax 请求访问 CodeIgniter Controller

javascript - 为什么 click() 不适用于附加元素?

javascript - jQuery 获取子元素的属性

javascript - 查找数组中链式递增的值

c# - SignalR Hub 未执行指定的 javascript

javascript - Typescript 转译是否处理从 ES6 到 ES5 的转译?

javascript - Next.js 获取SSR中的用户数据

jquery - 从元素中删除(软连字符)实体