簡體   English   中英

這兩個jQuery用法有什么區別

[英]What is the difference between these two jQuery usage

我是一個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>

在第二個實例中,代碼在<p>被解析到DOM樹之前執行,所以當它仍然有效時,無處輸出輸出文本。 換句話說, jQuery("p")匹配任何元素,所以.html() “什么都不做”。

您可以通過等待DOM完全解析來解決此問題:

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

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

好吧,似乎你的瀏覽器首先加載<head>部分,因此在第二個例子中沒有p元素。

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

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

  • 將腳本放在<body>標記之后(就像在第一個示例中一樣)

  • 或者你可以在ready事件被觸發后調用你的函數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM