如何使用jQuery找到具有特定ID的元素
问题是使用JQuery来确定一个具有特定id的元素是否存在。
- jQuery on()方法。这个方法为选定的元素和子元素添加一个或多个事件处理程序。
语法:
$(selector).on(event, childSelector, data, function, map)
- 参数:
- event。这是一个必要的参数。它指定了一个或多个事件或命名空间,以附加到选定的元素。在有多个事件值的情况下,这些值用空格分隔。事件必须是一个有效的。
- childSelector。它是可选的参数。它指定事件处理程序应该只附加到定义的子元素。
- data。它是可选参数。它指定要传递给函数的额外数据。
- function。它是必需的参数。它指定了事件发生时要运行的函数。
- map。它指定了一个事件地图({event:func(), event:func(), …}),有一个或多个事件添加到选定的元素,以及事件发生时要运行的函数。
-
jQuery length属性。length属性是用来计算jQuery对象的元素数量。
语法:
$(selector).length
例子1:在这个例子中,var name包含要检查的ID名称。首先,JQuery选择器通过var name检查ID,然后length属性被用来验证是否有东西被选中。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to find element with
specific id exists or not
</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style = "text-align:center;">
<h1 id = "h" style = "color:green;" >
GeeksForGeeks
</h1>
<p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;">
</p>
<button id = "button">
Click here
</button>
<p id = "GFG_DOWN" style =
"color:green; font-size: 20px; font-weight: bold;">
</p>
<script>
('#GFG_UP').
text("Click on button to check existence of particular ID");
var name = "h";
("button").on('click', function() {
var exist = "";
if(("#" + name).length == 0) {
exist = "Not Exists";
}
else {
exist = "Exists";
}
('#GFG_DOWN').text("Element of ID = '"
+ name + "' " + exist);
});
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
例子2:在这个例子中,要检查的ID名称直接在JQuery选择器中传递。首先JQuery选择器检查ID,然后length属性被用来验证是否有东西被选中。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to find element with
specific id exist or not
</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style = "text-align:center;">
<h1 id = "h" style = "color:green;" >
GeeksForGeeks
</h1>
<p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;">
</p>
<button id = "button">
Click here
</button>
<p id = "GFG_DOWN" style =
"color:green; font-size: 20px; font-weight: bold;">
</p>
<script>
('#GFG_UP').
text("Click on button to check existence of particular ID");
("button").on('click', function() {
var exist = "";
if(("#button").length == 0) {
exist = "Not Exists";
}
else {
exist = "Exists";
}
('#GFG_DOWN').text("Element of ID = 'button"
+ "' " + exist);
});
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。