當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


jQuery :selected用法及代碼示例


:selected選擇器用於選擇預選的選項元素。

注意:要僅檢索check-boxes或單選按鈕,請使用:選中的選擇器。

用法:



$(":selected")

以下示例說明了jQuery中的:selected選擇器:

範例1:本示例對所有預選元素使用CSS屬性。預選元素的背景色為紅色,由以下選擇器更改。

<!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:此示例類似於previous-one。

<!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>     

輸出:




相關用法


注:本文由純淨天空篩選整理自PranchalKatiyar大神的英文原創作品 jQuery | :selected Selector。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。