document.getElementById(id)找不到对象是怎么回事?
<input id= "cbChapter_0 " type= "checkbox " name= "cbChapter_0 " value= "1 "> <span> 第一章 </span>
<input id= "cbChapter_1 " type= "checkbox " name= "cbChapter_1 " value= "2 "> <span> 第二章 </span>
function FindCheckBox()
{
var values = " ";//选中CheckBox的值组合
var input = document.getElementsByTagName( "input ");
var n = input.length;
for(i=0;i <n;i++)
{
var id= "cbChapter_ "+i;
var tempObj=document.getElementById(id);
if(tempObj.tagName== "INPUT " && tempObj.type == "checkbox ")
{
if( tempObj.checked)
{
values = tempObj.value + ", ";
}
}
}
alert(values);
}
报错说var tempObj=document.getElementById(id);缺少对象
怎么解决阿?谢谢
------解决方案--------------------问题有可能是因为你页面上存在多个input而使i的值不能随你指定的顺序排列得出checkbox的id
可以这么写
<input id= "cbChapter_0 " name= "cbChapter " type= "checkbox " value= "1 "> <span> 第一章 </span>
<input id= "cbChapter_1 " name= "cbChapter " type= "checkbox " value= "2 "> <span> 第二章 </span>
<input onclick= "FindCheckBox(); " type= "button " value= "click me " />
<script>
function FindCheckBox()
{
var values = " ";//选中CheckBox的值组合
var cbChapter = document.getElementsByName( "cbChapter ");
var n = cbChapter.length;
for(i = 0;i < n;i++)
{
if( cbChapter[i].checked)
{
values += cbChapter[i].value + ", ";
}
}
alert(values);
}
</script>
功能应该是一样的吧