2012-09-15 47 views
3

林一個jQuery起動,所以如果它的錯誤的一個原諒我:)是什麼這兩個jQuery的使用

我只是想知道爲什麼把在做出這個腳本的工作位置不同內容之間的差異,雖然我的最好我認爲腳本保存在文檔的head部分。請解釋一下這個概念。

工作守則

<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Example 2</title> 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> 

</head> 

<body> 

<p> 
</p> 

<script type="text/javascript"> 
jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax); 
</script> 

</body> 
</html> 

不工作

<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Example 2</title> 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> 
<script type="text/javascript"> 
jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax); 
</script> 
</head> 

<body> 

<p> 
</p> 

</body> 
</html> 
+3

閱讀此:http://api.jquery.com/ready/ –

+0

@YouQi thx爲鏈接..jquery似乎非常浩瀚:) – Trialcoder

回答

8

在代碼中的<p>之前執行的第二個實例被解析爲DOM樹,因此,儘管它仍然有效沒有地方可以放入輸出文字。換句話說,jQuery("p")不匹配任何元素,因此.html()「什麼都不做」。

您可以通過等待DOM被完全處理解決這個問題:

jQuery(function() { 
    jQuery("p").html(...); 
}); 

,或者通過使用輸出機制,不依賴於現有<p>,如alert()console.log()

+0

Thx爲信息兄弟:) – Trialcoder

3

那麼,好像你的瀏覽器首先加載了<head>這個段,於是在第二個例子中就沒有p這個元件了。

在這兩種情況下,你應該把你的代碼包裝在$(function(){ ... })

1

如果將腳本放置在<body>元素的前面,則在加載/解析DOM樹之前執行該腳本。 <p>元素因此不存在並且無法找到。您可以:

  • 放置腳本<body>標籤後(如在你的第一個例子)

  • ,或者你可以調用你的函數後ready事件已被解僱:

    $(document).ready(function() { 
        jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax); 
    });