以下是我的javascript程序.我试图获取父div标签的所有子标签,但是当我运行程序document.getElementById('abc')时返回null.
function init(){
// currentDiv = document.getElementById("intro");
alert("working");
count = 0;
divs = document.getElementById('abc').getElementsByTagName("div");
alert("HI " + divs)
currentDiv = divs[count];
nextDiv = divs[count + 1]
count = count + 1;
}
window.onload = init();
Run Code Online (Sandbox Code Playgroud)
以下是我的div标签定义:
<div id='abc'>
<div></div>
</div>
Run Code Online (Sandbox Code Playgroud)
谢谢.
问题出在这一行:
window.onload = init();
Run Code Online (Sandbox Code Playgroud)
您正在运行init并将返回值设置为值window.onload.我的猜测是代码在DOM准备好之前执行,即在div存在之前执行.
试试这个:
window.onload = init;
Run Code Online (Sandbox Code Playgroud)