: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.jquery.com/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>

示範