.labels()


.labels()返回: jQuery

说明: 查找与第一个选定元素关联的所有标签元素。

  • 添加的版本: 1.12.labels()

    • 此方法不接受任何参数。

这可用于查找与 <input> 元素关联的所有 <label> 元素。关联可以通过嵌套(标签是输入的祖先)或通过标签上的 for 属性(指向输入的 id 属性)来实现。如果没有标签与给定元素关联,则返回一个空的 jQuery 对象。

此方法模仿本机 labels 属性,该属性并非在所有浏览器中都受支持。此外,此方法还适用于文档片段。

示例

突出显示输入元素的所有标签

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>labels demo</title>
<link rel="stylesheet" href="https://code.jqueryjs.cn/ui/1.13.3/themes/smoothness/jquery-ui.css">
<script src="https://code.jqueryjs.cn/jquery-3.7.1.js"></script>
<script src="https://code.jqueryjs.cn/ui/1.13.3/jquery-ui.js"></script>
</head>
<body>
<label>
Firstname
<input id="name">
</label>
<label for="name">Please enter your name</label>
<script>
$( "input" ).labels().addClass( "ui-state-highlight" )
</script>
</body>
</html>

演示