[英]GetElementsByTagName(tag).length
I tried to count the <li>
-Elements within an <ul>
-Listing. 我试图计数
<li>
-elements内的<ul>
-Listing。 I expected it to work like this: 我希望它像这样工作:
(The JavaScript): (JavaScript):
var ul = document.getElementById('listing');
function countLi(){
alert("There are "+ul.getElementsByTagName('li').length+" Li-Elements in this Documnet!");
}
(The HTML): (HTML):
<input type="button" onclick="countLi()" value="Count the Li's!"/>
<ul id="listing">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
It tells me, that "ul is null". 它告诉我,“ ul为空”。 So where is my fault?
那我的错在哪里?
Kind regards, vogti 亲切的问候,vogti
Edit: Ah, yeah. 编辑:嗯,是的。 I did a Fiddle for you .
我为你做了一个小提琴 。
Your problem is that this line: 您的问题是这一行:
var ul = document.getElementById('listing');
is executing before your ul
exists. 在您的
ul
存在之前执行。 Either move your whole script somewere below your </ul>
, put your code in a window.onload
/ $(document).ready
callback, or simply move that line into your function (which will also make your ul
variable be locally scoped to that function): 可以将整个脚本移到
</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!");
}
Try like this.Listing element not ready when your code block rendered. 像这样尝试。呈现代码块时,Listing元素未准备好。
function countLi(){
var ul = document.getElementById('listing');
alert("There are "+ul.getElementsByTagName('li').length+" Li-Elements in this Documnet!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.