需求如下,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>