JS怎样操作改变radio的状态
1个回答
展开全部
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>JS怎样操作改变radio的状态</title>
<script>
var radio = function(name){
this.name = ''; //单选框名字
this.members = []; //单选框的成员
this.init = function(name){ //初始化
var newMembers = []; //新的成员
this.name = name;
this.members = document.body.getElementsByTagName('input');
for(var i = 0; i < this.members.length; i++){
if( this.members[i].name == this.name ){
newMembers.push( this.members[i] );
}
}
this.members = newMembers; //覆盖
}
this.select = function(index){ //看这个函数就行,其他的请无视
for(var i = 0; i < this.members.length; i++){
if( i == index ){
this.members[i].checked = true;
}else{
this.members[i].checked = false;
}
}
}
this.init(name);
}
window.onload = function(){
window.sex = new radio('sex');
}
</script>
</head>
<body>
<div class="main">
<span>请选择你的性别:</span>
<input type="radio" name="sex" value="男" ><span>男</span>
<input type="radio" name="sex" value="女" ><span>女</span>
<hr />
<button onclick="sex.select(0)">选择男</button>
<button onclick="sex.select(1)">选择女</button>
<button onclick="sex.select(-1)">都不选</button>
</div>
</body>
</html>
只要控制radio元素checked属性即可
这里写了个案例(写完才发现,忘了检查类型了,不过不影响这题的回答)
附图:
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询