如何在jQuery中找到所有被禁用的元素
在这篇文章中,我们将学习如何使用jQuery找到页面上所有被禁用的元素。
方法: :disabled选择器可用于获取页面上所有当前禁用的元素。这些元素使用each()方法进行迭代。然后可以使用each()方法的函数中的this引用单独访问这些元素。
通过在disabled选择器前面指定元素的类型,可以选择一个特定类型的元素,否则页面上所有的元素都会被选中,如果它们是禁用的。例如,使用 “input:disabled “将只选择属于input类型的禁用元素。
语法:
$(".btn").click(function () {
let disabled_elems = "";
// Get all the disabled elements
$(":disabled").each(function (index) {
// Add a border to the elements
$(this).css("border", "10px red dashed");
// Add the IDs to the list
disabled_elems += "<li>"
+ ($(this).attr("id")) + "</li>";
});
$(".elems").html(disabled_elems);
});
HTML
下面的例子说明了上述方法。
示例:
<!DOCTYPE html>
<html>
<head>
<script src=
"https://code.jquery.com/jquery-3.3.1.min.js">
</script>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to find all elements that
are disabled in jQuery?
</b>
<!-- Define some elements with
the disabled attribute -->
<p><b>Inputs</b></p>
<input type="text" id="inp1" disabled />
<br><br>
<input type="text" id="inp2" />
<p><b>Buttons</b></p>
<button type="button" id="btn1">
Enabled Button
</button>
<br><br>
<button type="button" id="btn2" disabled>
Disabled Button
</button>
<p><b>Selects</b></p>
<select id="select1" disabled>
<option value="opt1">Option 1</option>
</select>
<br><br>
<select id="select2">
<option value="opt1">Option 1</option>
</select>
<br>
<p>
Click on the button to mark all
the disabled elements and
get their element ID
</p>
<button class="btn">
Get all disabled elements
</button>
<br><br>
<b>The ids of the disabled elements are:</b>
<ul class="elems"></ul>
<script>
(".btn").click(function () {
let disabled_elems = "";
// Get all the disabled elements
// using the :disabled selector
(":disabled").each(function (index) {
// Add a border to the elements
(this).css(
"border", "10px red dashed"
);
// Add the IDs to the list
disabled_elems += "<li>"
+ ((this).attr("id")) + "</li>";
});
$(".elems").html(disabled_elems);
});
</script>
</body>
</html>
HTML
输出: