jQuery ID 选择器

Sheeraz Gul 2024年2月15日
jQuery ID 选择器

jQuery 中有三种选择器; IDClassElement。本教程演示了如何在 jQuery 中使用 ID 选择器。

jQuery ID 选择器

ID 选择器将选择具有给定 id 属性的单个元素。语法很简单 $(#ID),其中 ID 是元素 ID。

如果 ID 包含句点或冒号等特殊字符,我们必须使用反斜杠转义这些字符。ID 选择器返回用找到的元素填充的数组。

例如:

  1. #DemoID 将选择具有给定 ID 的单个元素。
  2. Div#DemoID 将选择具有给定 ID 的 div

让我们看一个在 jQuery 中使用 ID 选择器的示例。

<!DOCTYPE HTML>
<html>
    <head>
        <title>jQuery ID Selector</title>
        <script type = "text/javascript" src = "https://code.jquery.com/jquery-1.10.2.js"> </script>

        <script type = "text/javascript" language = "javascript">
            $(document).ready(function() {
                $("#DemoDiv1").css("background-color", "lightblue");
            });
        </script>
    </head>

    <body>
        <div id = "DemoDiv1">
            <p>This is the First Div.</p>
        </div>

        <div id = "DemoDiv2">
            <p>This is the Second Div.</p>
        </div>

        <div class = "DEMO1" id = "DemoDiv3">
            <p>This is the Third Div.</p>
        </div>
		<div class = "DEMO2" id = "DemoDiv1">
            <p>This is the Fourth Div.</p>
        </div>
    </body>
</html>

上面的代码将选择具有唯一 ID 的元素并更改其背景颜色;由于此代码有两个具有相同 ID 的元素,它只会选择第一个,因为 ID 始终是唯一的。见输出:

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 Selector