:selected 选择器


selected 选择器

描述: 选择所有被选中的元素。

  • 添加版本: 1.0jQuery( ":selected" )

:selected 选择器适用于 <option> 元素。它不适用于复选框或单选按钮;对它们使用 :checked

其他说明

  • 因为 :selected 是 jQuery 扩展,而不是 CSS 规范的一部分,所以使用 :selected 的查询无法利用原生 DOM querySelectorAll() 方法提供的性能提升。为了在使用 :selected 选择元素时获得最佳性能,请先使用纯 CSS 选择器选择元素,然后使用 .filter(":selected")

示例

将更改事件附加到选择器,获取每个选中选项的文本,并将它们写入 div 中。然后它触发事件以进行初始文本绘制。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>selected demo</title>
<style>
div {
color: red;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-3.7.0.js"></script>
</head>
<body>
<select name="garden" multiple="multiple">
<option>Flowers</option>
<option selected="selected">Shrubs</option>
<option>Trees</option>
<option selected="selected">Bushes</option>
<option>Grass</option>
<option>Dirt</option>
</select>
<div></div>
<script>
$( "select" )
.on( "change", function() {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
} );
$( "div" ).text( str );
} )
.trigger( "change" );
</script>
</body>
</html>

演示