简单的元素个数问题

net205 2006-09-28 07:51:01
如下,Test1正常,而Test2没反应,像xid有一个元素,得到的元素长度xid.length却为"undefined",如果要处理可能得分2种情况判断处理,有没有简单方便的办法 ???

<script>
function test1(){
var ElementLen = document.frmtest.id.length;
for(var i=0;i<ElementLen;i++){
alert(i+":"+document.frmtest.id[i].checked);
}
}
function test2(){
var ElementLen = document.frmtest.xid.length; //undefined
for(var i=0;i<ElementLen;i++){
alert(i+":"+document.frmtest.xid[i].checked);
}
}

</script>

<form id="frmtest" name="frmtest">
<input id="id" name="id" type="checkbox" value="1">1
<input id="id" name="id" type="checkbox" value="2">2
<input id="id" name="id" type="checkbox" value="3">3
  <button onclick="test1()">Test1</button>
<br/>
<input id="xid" name="xid" type="checkbox" value="01">01
  <button onclick="test2()">Test2</button>
<br/>
</form>
...全文
88 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
net205 2006-09-28
  • 打赏
  • 举报
回复
结账......
net205 2006-09-28
  • 打赏
  • 举报
回复
多谢2位老兄,,明白了。。只怪偶学习时没认真,没用心。

--------------
getElementById Returns a reference to the first object with the specified value of the ID attribute.
getElementsByName Retrieves a collection of objects based on the value of the NAME attribute.
getElementsByTagName Retrieves a collection of objects based on the specified element name.
孟子E章 2006-09-28
  • 打赏
  • 举报
回复
var ElementLen = document.getElementsByName("xid")
这种写法不管一个还是多个,都正常
hbhbhbhbhb1021 2006-09-28
  • 打赏
  • 举报
回复
1个的时候不是数组,所以没有length属性
写成
document.getElementsByName("xid").length
孟子E章 2006-09-28
  • 打赏
  • 举报
回复
var ElementLen = document.getElementsByName("xid")
通吃2种情况

87,918

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧