我试图计算 <li>
-<ul>
中的元素- list 。我希望它能像这样工作:
(JavaScript):
var ul = document.getElementById('listing');
function countLi(){
alert("There are "+ul.getElementsByTagName('li').length+" Li-Elements in this Documnet!");
}
(HTML):
<input type="button" onclick="countLi()" value="Count the Li's!"/>
<ul id="listing">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
它告诉我,“ul 为空”。那么我的错在哪里呢?
亲切的问候, 沃蒂
编辑: 啊,是的。 I did a Fiddle for you .
最佳答案
你的问题是这一行:
var ul = document.getElementById('listing');
在您的 ul
之前执行存在。要么将你的整个脚本移动到你的 </ul>
下面, 将您的代码放在 window.onload
中/$(document).ready
回调,或者只是将该行移动到您的函数中(这也会使您的 ul
变量在该函数的本地范围内):
function countLi(){
var ul = document.getElementById('listing');
alert("There are "+ul.getElementsByTagName('li').length+" Li-Elements in this Documnet!");
}
关于javascript - GetElementsByTagName(标签).length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10819972/