总有人间一两风,填我十万八千梦

jQuery .:selected Selector 用法 手册 | 示例代码

jQuery开发手册 归档 911℃ 0评论

描述: 获取 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="https://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>

转载请注明:悠然品鉴 » jQuery .:selected Selector 用法 手册 | 示例代码

喜欢 (0)or分享 (0)
发表我的评论
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
(1)个小伙伴在吐槽
  1. 简洁实用,好文章!
    ChuHai52021-10-12 07:44 回复