什麼時候在$(document)裏面定義javascript函數。準備好(),你什麼時候沒有?
如果職能應該是全球可訪問(這可能表明你的應用程序的設計不好),那麼你必須定義它們的ready
處理程序之外。
僅僅是把$(document).ready()中的所有javascript代碼放在裏面足夠安全嗎?
見上文。
當你不這樣做時會發生什麼?
取決於您的JavaScript代碼在做什麼以及它的位置。最糟糕的情況是,您將會遇到運行時錯誤,因爲您正試圖在DOM元素存在之前訪問它們。如果您的代碼位於head
中,並且您不僅定義函數,而且已嘗試訪問DOM元素,則會發生這種情況。
例如,我使用通常的jQuery選擇器,當您點擊東西時會執行某些操作。如果你沒有用document.ready包裝這些有什麼危害?
有沒有 「傷害」 本身。如果腳本位於head
中,那麼它將不起作用,因爲DOM元素尚不存在。這意味着,jQuery無法找到並將處理程序綁定到它們。
但是,如果你在結束body
標記之前放置腳本,那麼DOM元素將存在。
爲了安全起見,只要你想訪問DOM元素,將在ready
事件處理到DOM被加載後才能被調用的函數這些調用。
由於jQuery tutorial(你應該看它)已經指出:
我們什麼時候使用jQuery讀取或操縱文檔對象模型(DOM)做
由於幾乎所有的東西,我們需要確保我們開始添加事件等,只要DOM準備就緒。
要做到這一點,我們註冊的文件ready事件。
$(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>
感謝。我想知道這是爲什麼我會出現一些奇怪的行爲。 – Dave31415 2012-03-11 18:38:09