需求如下,radio已經選中,再點擊,取消選中狀態。
效果如鏈接:演示地址
直接上代碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <input type="radio" name="sex" id="sex1" value="1"><label for='sex1'>男</label> <input type="radio" name="sex" id="sex0" value="0"><label for='sex0'>女</label> <script> var selectID = null; var els = document.querySelectorAll("[name=sex]") for (el of els) { el.addEventListener("click", function() { if (selectID == this.id && selectID) { this.checked = "" selectID = null; } else { selectID = this.id; } }) } function GetRadioValue(radioName) { var radios = document.getElementsByName(radioName); for (var i = 0; i < radios.length; i++) { var radio = radios.item(i); if (radio.checked) { return radio.value; } } } </script> </body> </html>