在CSS中,我們可以使用屬性選擇器來統(tǒng)計頁面中特定屬性的元素數(shù)量,對于單選按鈕(radio)我們可以使用[type="radio"]
來選擇所有的單選按鈕元素,我們可以使用JavaScript的length
屬性來獲取選中的元素數(shù)量。
以下是一個簡單的示例代碼,展示了如何實現(xiàn)這一功能:
<!DOCTYPE html> <html> <head> <title>統(tǒng)計單選按鈕數(shù)量</title> <script> function countRadios() { var radios = document.querySelectorAll('input[type="radio"]'); var count = radios.length; console.log('單選按鈕數(shù)量:' + count); } </script> </head> <body> <input type="radio" id="radio1"> <input type="radio" id="radio2"> <input type="radio" id="radio3"> <button onclick="countRadios()">統(tǒng)計數(shù)量</button> </body> </html>
在這個示例中,我們首先在HTML中定義了三個單選按鈕,并為每個按鈕分配了一個***的ID,在JavaScript中,我們定義了一個名為countRadios
的函數(shù),該函數(shù)使用document.querySelectorAll
方法選擇了所有類型為"radio"的輸入元素,并使用length
屬性獲取了選中的元素數(shù)量,我們在HTML中添加了一個按鈕,用于觸發(fā)countRadios
函數(shù)并顯示結果。
這只是一個簡單的示例,實際使用時可能需要根據(jù)具體需求進行調整,如果頁面中有多個表單或容器,可能需要更***的選擇器來定位到特定的單選按鈕組。