jQuery :selected 選擇器



jQuery 中的:selected 選擇器用於選擇 <select> 元素中當前選中的 <option> 元素。

此選擇器不能用於複選框或單選按鈕。 需要使用:checked 選擇器。

語法

以下是 jQuery 中 :selected 選擇器的語法:

$(":selected")

引數

以下是此方法的引數:

  • ":selected" − 此選擇器篩選指定 <select> 元素中選中的 <option> 元素。

示例 1

在下面的示例中,我們演示了 jQuery 中 :selected 選擇器的基本用法:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
        $(":selected").css("background-color", "green")
    });
  </script>
</head>
<body>
  <select>
    <option value="1">Option 1</option>
    <option value="2" selected>Option 2</option>
    <option value="3">Option 3</option>
  </select>
</body>
</html>

執行上述程式時,:selector 選擇預先選中的 option 元素 ("Option 2")。

示例 2

在此示例中,我們預先選擇了多個下拉選項:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        var selectedOptions = [];
        $(":selected").each(function(){
          selectedOptions.push($(this).text());
        });
        alert("Selected options: " + selectedOptions.join(", "));
      });
    });
  </script>
</head>
<body>
  <select id="multiSelect" multiple>
    <option value="1">Option 1</option>
    <option value="2" selected>Option 2</option>
    <option value="3" selected>Option 3</option>
    <option value="4">Option 4</option>
  </select>
  <button>Get Selected Values</button>
</body>
</html>

程式執行後,一個警告框將顯示所有選中選項的文字,用逗號分隔。

jquery_ref_selectors.htm
廣告
© . All rights reserved.