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