日期:2014-05-16  浏览次数:20474 次

getElementsByTagName获得数组长度一直为0
HTML code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>Test</title>
<style type="text/css">
    ul{
        list-style:none;
    }
    li{
        background-image:url(Winter.jpg);
        width:100px;
    }
</style>
<script type="text/javascript">
    var lis=document.getElementsByTagName("li");
    for(var i=0;i<lis.length;i++){
        lis[i].onmouseover=function(){
            this.style.backgroundImage="url(Sunset.jpg)";
        }
        lis[i].onmouseout=function(){
            this.style.backgroundImage="url(Winter.jpg)";
        }
    }
</script>
</head>
<body>
    <ul>
        <li>aaa</li>
        <li>bbb</li>
        <li>ccc</li>
    </ul>
</body>
</html>




var lis=document.getElementsByTagName("li");
这一行调试了,为什么lis数组长度一直为0,如何解决

------解决方案--------------------
js代码放置的位置不对,要么像下面这样放到ul标签之后,要么将代码写到window.onload = function() {}函数中。

JS是解释型语言,边加载边解释,只有目标对象被加载到DOM树以后才能获取和操作。

HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>Test</title>
<style type="text/css">
    ul{
        list-style:none;
    }
    li{
        background-image:url(Winter.jpg);
        width:100px;
    }
</style>
</head>
<body>
    <ul>
        <li>aaa</li>
        <li>bbb</li>
        <li>ccc</li>
    </ul>
<script type="text/javascript">
    var lis=document.getElementsByTagName("li");
    for(var i=0;i<lis.length;i++){
        lis[i].onmouseover=function(){
            this.style.backgroundImage="url(Sunset.jpg)";
        }
        lis[i].onmouseout=function(){
            this.style.backgroundImage="url(Winter.jpg)";
        }
    }
</script>

</body>
</html>

------解决方案--------------------
楼上正解
------解决方案--------------------
还可以
window.onload=funtion(){
var lis=document.getElementsByTagName("li");
for(var i=0;i<lis.length;i++){
lis[i].onmouseover=function(){
this.style.backgroundImage="url(Sunset.jpg)";
}
lis[i].onmouseout=function(){
this.style.backgroundImage="url(Winter.jpg)";
}
}
}