:selected 选择器
分类:选择器 > 表单选择器 | 选择器 > jQuery扩展选择器
selected selector
描述:选择所有的<select>被选中的<option>元素。
加入于: 1.0
jQuery( ":selected" ):selected只对<select>起作用。它不能对勾选框或者单选钮起作用;请对它们使用:checked选择器。
其它说明
- 因为
:selected是一个jQuery扩展,并不是CSS规范文档的一部分,使用:selected查询,不能充分利用原生DOM的querySelectorAll()方法来提高性能。要想在使用:selected选择元素时获得最佳性能,请先使用一个纯CSS选择器选择元素,然后使用.filter(":selected")作筛选。
示例
把change事件附加到<select>上,以获得每个选中项的文本文件,并把它写到div中。然后它触发了初始化文本绘制的事件。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>selected demo</title>
<style>
div {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.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>