我有一个HTML页面的源代码如下 -如何计算HTML页面的按钮数量?
<html>
<script type="text/javascript">
function jsMeth() {
alert('Count of buttons : '+document.getElementsByTagName('button').length);
}
</script>
<input type="button" value="button 1" id="btn1" name="btn1" /><br>
<input type="button" value="butto 2" id="btn2" name="btn2" /><br><br>
<input type="button" value="Calculate button count" id="btn3" name="btn3" onclick="jsMeth();"/>
</html>
我的基本目的是,当我点击有键ID“btn3”,它应该显示在我的HTML页面的按钮数量(本情况3)。但不知何故,它总是显示为0。
感谢您的快速回复。由于所有的你的建议,我已经修改我的代码如下 -
<html>
<script type="text/javascript">
function jsMeth() {
alert('Count of buttons : '+document.querySelectorAll('[type=button]').length);
}
</script>
<input type="button" value="button 1" id="btn1" name="btn1" /><br>
<input type="button" value="butto 2" id="btn2" name="btn2" /><br><br>
<input type="button" value="Calculate button count" id="btn3" name="btn3" onclick="jsMeth();"/>
</html>
但现在我得到下面的错误 -
Message: Object doesn't support this property or method
Line: 4
Char: 9
Code: 0
URI: file:///C:/Documents%20and%20Settings/556996/Desktop/demohtml.html
我在IE8测试。请帮忙!
感谢, Kartic
所有这些元素的标签名称是'input'。 – 2013-05-08 19:36:32
是的布赖恩,我可以使用document.getElementByTagName(“输入”),然后检查类型按钮,但我想知道如果我可以不做所有这些东西的所有按钮元素。现在我怀疑这是没有选择的。是吗? – tik 2013-05-09 19:27:11