jQuery - 語法



jQuery 用於從 HTML 文件中選擇任何 HTML 元素,然後對該選定的元素執行任何操作。要選擇 HTML 元素,可以使用 jQuery 選擇器,我們將在下一章詳細學習這些選擇器。現在讓我們先看看基本的jQuery 語法,以瞭解如何查詢、選擇或查詢元素,然後對選定的元素執行操作。

文件就緒事件

在深入瞭解jQuery 語法之前,讓我們先嚐試瞭解什麼是文件就緒事件。實際上,在我們執行任何 jQuery 語句之前,我們希望等待文件完全載入。這是因為 jQuery 在 DOM 上執行,如果在執行 jQuery 語句之前 DOM 未完全可用,那麼我們將無法獲得期望的結果。

以下是文件就緒事件的基本語法

$(document).ready(function(){

  // jQuery code goes here...

});

或者,您也可以使用以下語法表示文件就緒事件

$(function(){

  // jQuery code goes here...

});
您應該始終將文件就緒事件塊放在<script>...</script>標籤內,並且您可以將此指令碼標籤放在<head>...</head>標籤內或頁面底部<body>標籤關閉之前。

您可以使用這兩種語法中的任何一種,將您的 jQuery 程式碼放在此塊內,該塊僅在完整 DOM 下載並準備好進行解析時才執行。

jQuery 語法

以下是選擇 HTML 元素然後對選定的元素執行某些操作的基本語法

$(document).ready(function(){
    $(selector).action()
});

任何 jQuery 語句都以美元符號$開頭,然後我們將選擇器放在括號()內。此語法$(selector)足以返回選定的 HTML 元素,但如果您必須對選定的元素執行任何操作,則需要action()部分。

工廠函式$()jQuery()函式的同義詞。因此,如果您使用的是任何其他 JavaScript 庫,其中 $ 符號與其他內容衝突,則可以將$符號替換為 jQuery 名稱,並且可以使用函式jQuery()代替$()

示例

以下是一些說明 jQuery 基本語法的示例。以下示例將從 HTML 文件中選擇所有<p>元素,並隱藏這些元素。嘗試點選圖示run button執行以下 jQuery 程式碼

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.tw/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("p").hide()
   });
</script>
</head>
<body>
   <h1>jQuery Basic Syntax</h1>

   <p>This is p tag</p>
   <p>This is another p tag</p>
   <span>This is span tag</span>
   <div>This is div tag</div>
</body>
</html>

讓我們使用jQuery()方法而不是$()方法重寫上述示例

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.tw/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      jQuery("p").hide()
   });
</script>
</head>
<body>
   <h1>jQuery Basic Syntax</h1>

   <p>This is p tag</p>
   <p>This is another p tag</p>
   <span>This is span tag</span>
   <div>This is div tag</div>
</body>
</html>

以下是將所有<h1>元素的顏色更改為紅色的 jQuery 語法。嘗試點選圖示run button執行以下 jQuery 程式碼

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.tw/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("h1").css("color", "red")
   });
</script>
</head>
<body>
   <h1>jQuery Basic Syntax</h1>

   <p>This is p tag</p>
   <span>This is span tag</span>
   <div>This is div tag</div>
</body>
</html>

類似地,您可以更改所有類為“red”的元素的顏色。嘗試點選圖示run button執行以下 jQuery 程式碼

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.tw/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $(".red").css("color", "red")
   });
</script>
</head>
<body>
   <h1>jQuery Basic Syntax</h1>

   <p>This is p tag</p>
   <span>This is span tag</span>
   <div class="red">This is div tag</div>
</body>
</html>

到目前為止,我們已經看到了 jQuery 語法的非常基本的示例,以便讓您清楚地瞭解 jQuery 將如何在 HTML 文件上執行。您可以修改上述框中給出的程式碼,然後嘗試執行這些程式以檢視它們在實際中的執行情況。

廣告