日期:2014-05-16  浏览次数:20341 次

如何用getElementsById来引用单选框
页面上
<input   type= "radio "   name= "shuiguo "   id= "shuiguo "   value= "3 ">
<input   type= "radio "   name= "shuiguo "   id= "shuiguo "   value= "2 ">
<input   type= "radio "   name= "shuiguo "   id= "shuiguo "   value= "1 ">

为什么我写  

var   bbb   =   document.getElementsById( "shuigui ");

alert(bbb)提示htmlinput是有值的

但是一旦写   alert(bbb[0])或者   alert(bbb[1].checked)   就报找不到对象,属性不存在之类的错误?

------解决方案--------------------
先给你指出两点问题:
1.id是一个页面中标志一个唯一控件的名字,所以不应该出现一个以上同名的id,你可以用getElementsByName()来得到数组;
2.radio的值不能象select一样,得到对象后用value之类的就知道选哪个了,要用数组来一个一个的判断,不过要从后台得到值的话好象到是简单点.所以alert至少要写成alert(bbb[1].checked== "checked ");
------解决方案--------------------
或者可以换个思路:
<html xmlns= "http://www.w3.org/1999/xhtml ">
<head>
<meta http-equiv= "Content-Type " content= "text/html; charset=gb2312 " />
<title> 无标题文档 </title>
<script language= "javascript ">
var radioValue = 0;
function aa(){
alert(radioValue);

}
function set(arg){
radioValue = arg.value;
alert(arg.value);
}

</script>
</head>

<body>
<form id= "form1 " name= "form1 " method= "post " action= " ">
<input type= "radio " name= "radiobutton " value= "1 " onClick= "set(this) "/>
<input type= "radio " name= "radiobutton " value= "2 " onClick= "set(this) "/>


<input type= "button " value= "aaaaa " onclick= "aa() " />
</form>
</body>
</html>