我对jQuery中的document.ready有些困惑。
在何时应该在$(document).ready()内定义javascript函数?在何时不需要?
是否将所有javascript代码都放在$(document).ready()内就足够安全了?
如果不这样做会发生什么?
例如,我使用常规的jQuery选择器,在单击元素时执行某些操作。如果不将它们包装在document.ready内,会有什么危害?
只会在页面加载前瞬间单击元素才会导致问题吗?或者会有其他问题?
我对jQuery中的document.ready有些困惑。
在何时应该在$(document).ready()内定义javascript函数?在何时不需要?
是否将所有javascript代码都放在$(document).ready()内就足够安全了?
如果不这样做会发生什么?
例如,我使用常规的jQuery选择器,在单击元素时执行某些操作。如果不将它们包装在document.ready内,会有什么危害?
只会在页面加载前瞬间单击元素才会导致问题吗?或者会有其他问题?
ready
处理程序之外定义它们。本质上没有“伤害”。如果脚本位于中,则无法正常工作,因为DOM元素尚不存在。这意味着,jQuery无法找到并绑定处理程序。
但是,如果将脚本放置在关闭的标记之前,那么DOM元素将存在。
ready
事件处理程序中或仅在DOM加载后调用的函数中。As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.
To do this, we register a ready event for the document.
$(document).ready(function() { // do stuff when DOM is ready });
提供一个更完整的示例:
<html>
<head>
<!-- Assuming jQuery is loaded -->
<script>
function foo() {
// OK - because it is inside a function which is called
// at some time after the DOM was loaded
alert($('#answer').html());
}
$(function() {
// OK - because this is executed once the DOM is loaded
$('button').click(foo);
});
// OK - no DOM access/manipulation
alert('Just a random alert ' + Math.random());
// NOT OK - the element with ID `foo` does not exist yet
$('#answer').html('42');
</script>
</head>
<body>
<div id="question">The answer to life, the universe and everything</div>
<div id="answer"></div>
<button>Show the answer</button>
<script>
// OK - the element with ID `foo` does exist
$('#answer').html('42');
</script>
</body>
</html>
document.ready
处理程序在浏览器加载完DOM并准备好进行操作时触发。
是否应该使用它取决于您放置自定义脚本的位置。如果您将它们放在文档末尾,紧接着关闭的</body>
标记之前,您不需要使用document.ready
,因为在您的脚本执行时,DOM已经被加载,您可以操作它。
另一方面,如果您将脚本放在文档的<head>
部分中,您应该使用document.ready
确保DOM在尝试修改它或将事件处理程序附加到各个元素之前完全加载。如果您不这样做,并且尝试将例如.click
事件处理程序附加到按钮,则此事件将永远不会触发,因为在您的脚本运行时,您用于查找按钮的jQuery选择器未返回任何元素,您没有成功地附加处理程序。
当您需要等待DOM加载后再执行代码时,请将代码放在$(document).ready
中。如果代码不需要先等待DOM存在才能运行,则可以将其放在$(document).ready之外。
顺便说一下,$(function() { })
是$(document).ready();
的简写。
$(function() {
//stuff here will wait for the DOM to load
$('#something').text('foo'); //should be okay
});
//stuff here will execute immediately.
/* this will likely break */
$('#something').text('weee!');
$()
中传递任何函数引用,并且当文档准备就绪时它会自动启动:$(myfunction)
。由于少了一个闭包,因此可以节省一些内存。 - Ben Lesh$(document).ready(myfunction)
和 $(myfunction)
是等价的。 - Ben Lesh
ready
处理程序,什么不必要。 - Felix Kling