在 jQuery 中通過 ID 獲取元素

Sheeraz Gul 2024年2月15日
  1. 在 JavaScript 中通過 ID 獲取元素
  2. 在 jQuery 中按 ID 獲取元素
在 jQuery 中通過 ID 獲取元素

在 JavaScript 中,我們可以使用 document.getElementById() 方法通過 ID 獲取元素。在 jQuery 中,我們可以使用 $('#contents') 通過 ID 獲取元素。

本教程演示瞭如何使用這兩種方法通過 ID 獲取元素。

在 JavaScript 中通過 ID 獲取元素

document.getElementById() 是最流行的通過 ID 獲取元素的方法。此方法主要用於網頁設計中以更改元素的值或獲取該元素。

此方法的語法是:

document.getElementById('id')

讓我們嘗試一個示例,使用此方法通過 ID 獲取元素:

<!DOCTYPE html>
<html>
<head>
    <title>
        Select element by ID in javascript
    </title>
</head>

<body style="border: 4px solid blue; min-height: 300px; text-align: center;">

    <h1 style="color:blue;" id="delftstack">
        DELFTSTACK
    </h1>

    <script>
        setTimeout(function() {
            document.getElementById('delftstack').style.color = "green"
            }, 3000);
    </script>
</body>
</html>

上面的程式碼獲取 h1 元素 ID 並在超時時更改其顏色。見輸出:

JavaScript 通過 ID 獲取元素

在 jQuery 中按 ID 獲取元素

jQuery 有一個更簡單的方法來通過 ID 選擇元素。jQuery 有一個 ID 選擇器,可以選擇具有唯一 ID 的元素。

此方法的語法是:

$("#idname");

讓我們試試 jQuery 中的示例,它將通過 ID 獲取元素的背景來改變它:

<!DOCTYPE html>
<html>

<head>
    <title>
    Select element by ID in JQuery
    </title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>

<body style="border: 4px solid blue; min-height: 300px; text-align: center;">

    <h1 style="color:blue;" id="delftstack">
        DELFTSTACK
    </h1>
    <script>
        setTimeout(function () {
            $('#delftstack').css("background-color", "yellow");;
        }, 3000);
    </script>
</body>
</html>

請參閱此程式碼的輸出:

jQuery 通過 ID 獲取元素

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相關文章 - jQuery Element