cvo*_*igt 2 javascript html5 dom
我试图在<li>-Listing中计算-Elements <ul>.我希望它能像这样工作:
(JavaScript):
var ul = document.getElementById('listing');
function countLi(){
alert("There are "+ul.getElementsByTagName('li').length+" Li-Elements in this Documnet!");
}
Run Code Online (Sandbox Code Playgroud)
(HTML):
<input type="button" onclick="countLi()" value="Count the Li's!"/>
<ul id="listing">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>?
Run Code Online (Sandbox Code Playgroud)
它告诉我,"ul为null".那我的错在哪里?
亲切的问候,vogti
编辑:啊,是的.我为你做了一个小提琴.
你的问题是这一行:
var ul = document.getElementById('listing');
Run Code Online (Sandbox Code Playgroud)
在你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!");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1103 次 |
| 最近记录: |