在 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