• jQuery Video Tutorials

jQuery :checked 選擇器



jQuery 中的:checked 選擇器用於選擇所有已勾選或選中的元素。

它適用於型別為“checkbox”或“radio”的<input> 元素,以及<select> 下拉列表中的<option> 元素。

語法

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

$(":checked")

引數

以下是此方法的引數:

  • ":checked" − 此選擇器選擇整個文件中所有已勾選的元素。

示例 1

在以下示例中,我們使用“:checked”來選擇所有已勾選的複選框:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
          $(":checked").wrap("<span style='background-color:yellow'>")
        });
    </script>
</head>
<body>
    <h1>Select Your Interests</h1>
    <label><input type="checkbox" value="Music" checked> Music</label><br>
    <label><input type="checkbox" value="Sports"> Sports</label><br>
    <label><input type="checkbox" value="Reading"> Reading</label><br>
    <label><input type="checkbox" value="Traveling"> Traveling</label><br>
    <div id="result"></div>
</body>
</html>

當我們執行上述程式時,已勾選的複選框將被選中,並用一個具有黃色背景色的<span> 元素包裹。

示例 2

在此示例中,我們使用“:checked”來選擇所有已勾選的單選按鈕:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
          $(":checked").wrap("<span style='background-color:yellow'>")
        });
    </script>
</head>
<body>
    <h1>Select Your Interests</h1>
    <label><input type="radio" value="Music" checked> Music</label><br>
    <label><input type="radio" value="Sports" checked> Sports</label><br>
    <label><input type="radio" value="Reading"> Reading</label><br>
    <label><input type="radio" value="Traveling"> Traveling</label><br>
    <div id="result"></div>
</body>
</html>

執行上述程式後,已勾選的單選按鈕將被選中,並用一個具有黃色背景色的<span> 元素包裹。

jquery_ref_selectors.htm
廣告

© . All rights reserved.