现在的位置: 首页 > 综合 > 正文

javascript下一种表单元素获取方法存在的问题

2012年03月08日 ⁄ 综合 ⁄ 共 1077字 ⁄ 字号 评论关闭

一. 测试环境
浏览器: IE6+, FF 3.5.5, Opera 10, Chrome 4.0.249, Safari 4.0.3

二. 例子

复制代码 代码如下:
<form name="test-form" action="" method="">
<input type="checkbox" name="kk">
<form>
<script type="text/javascript">
var oForm = document.forms['test-form'],
eles = oForm.elements['kk'];
alert(eles.length); // undefined
alert(eles.nodeType); // 1
</script>

三. 解决方法(我想到的方法是改变获取方式, 基于YUI)

复制代码 代码如下:
<script type="text/javascript">
var oForm = document.forms['test-form'],
eles = YAHOO.util.Dom.getElementsBy(function(el) {
return el.type === 'checkbox' && el.name === 'kk';
}, 'input', oForm);
alert(eles.length); // 1
</script>

document.formname.inputname

这个问题我之前已经遇到过一次了,但是这次又忘记了,依然又犯错了,所以我必须要记录一下。

看一下这个例子:

复制代码 代码如下:
<form name="hehe">
<input type="checkbox" name="haha" />
</form>
<form name="hehe2">
<input type="checkbox" name="haha" />
<input type="checkbox" name="haha" />
</form>
<script type="text/javascript">
document.write(document.hehe.haha.length);
document.write('<br />');
document.write(document.hehe2.haha.length);
</script>

演示

xmlns="http://www.w3.org/1999/xhtml">


抱歉!评论已关闭.