在js中如何使用单选框

方法一

先用getElementsByName筛选出需要的单选框元素(type="radio"),循环检查radio.checked是否为true
测试用的是菜鸟的网页测试因为偶然学到这里

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function displayResult(){
    var colors=document.getElementsByName("colors");
    for(i=0;i<colors.length;i++){
        if(colors[i].checked){
            alert(colors[i].id);
        }
    }
}
</script>
</head>
<body>

<form>
你更喜欢哪种颜色?<br>
<input type="radio" name="colors" id="red">红色<br>
<input type="radio" name="colors" id="blue">蓝色<br>
<input type="radio" name="colors" id="green">绿色
</form>
<button type="button" onclick="displayResult()">显示 input 内容</button>

</body>
</html>

方法二

直接在radio元素中添加onclick="getValue(this.value)"
然后覆写这个方法实现功能

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function getValue(id){
    alert(id);
}
</script>
</head>
<body>

<form>
你更喜欢哪种颜色?<br>
<input type="radio" name="colors" id="red" onclick="getValue(this.id)">红色<br>
<input type="radio" name="colors" id="blue" onclick="getValue(this.id)">蓝色<br>
<input type="radio" name="colors" id="green" onclick="getValue(this.id)">绿色
</form>


</body>
</html>


很郁闷,发出了信息,然后才会改变单选框,不过不跳出信息大概不会有这个问题,直接改变就可以了。

猜你喜欢

转载自www.cnblogs.com/Stratford-International/p/12411246.html