:selected Selector


selected selector

描述: 获取 select 元素中所有被选中的元素。

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

:selected 选择器只为适用于为<option>元素。它不适用复选框和单选框,复选框和单选框请使用:checked

Additional Notes(其他注意事项):

  • 因为:selected 是一个 jQuery 延伸出来的选择器,并不是的CSS规范的一部分,使用:selected 查询不能充分利用原生DOM提供的querySelectorAll() 方法来提高性能。为了当使用:selected 的时候在现代浏览器上获得更佳的性能,首先使用纯CSS选择器选择元素,然后使用.filter(":selected")代替.

例子:

在 select 元素上添加 change 事件,将选中的 option 元素的文本写入一个 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
<!DOCTYPE html>
<html>
<head>
<style>
div { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.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").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.trigger('change');
</script>
</body>
</html>

Demo: