jQuery :selected 选择器
jQuery :selected selector是用来选择那些预选的选项元素。
注意:要只检索复选框或单选按钮,请使用:checked选择器。
语法:
$(":selected")
下面的例子说明了jQuery中的:selected选择器。
例子1:这个例子对所有预选元素使用CSS属性。预选元素的背景色是红色,由 :selected selector 改变。
<!DOCTYPE html>
<html>
<head>
<title>
jQuery | :selected Selector
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- Script to set style to the selected selector -->
<script>
(document).ready(function () {
(":selected").css("background-color", "green");
$(":selected").css("color", "white");
});
</script>
<!-- CSS property to set Style to the element -->
<style>
option {
font-weight: bold;
font-size: 25px;
color: green;
}
select {
font-weight: bold;
font-size: 25px;
color: green;
}
</style>
</head>
<body style="text-align:center;">
<h1>
jQuery | :selected Selector
</h1>
<select>
<option>GFG_1</option>
<option selected="selected">GFG_2</option>
<option>GFG_3</option>
<option>GFG_4</option>
</select>
</body>
</html>
输出:
例子2:这个例子与前一个例子类似。
<!DOCTYPE html>
<html>
<head>
<title>
jQuery | :selected Selector
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- Script to set background-color of
selected element -->
<script>
(document).ready(function () {
(":selected").css("background-color", "green");
});
</script>
<style>
option {
font-weight: bold;
font-size: 25px;
}
select {
font-weight: bold;
font-size: 25px;
}
</style>
</head>
<body style="text-align:center;">
<h1>
jQuery | :selected Selector
</h1>
<select>
<option selected="selected">Computer Network</option>
<option>Data Structure</option>
<option>Algorithm</option>
<option>Operating System</option>
</select>
</body>
</html>
输出: