首页 新闻 赞助 找找看

javaScript全局变量问题

0
[已解决问题] 解决于 2013-11-18 23:00

下面的代码中的全局变量divElement在匿名函数中赋值以后,为什么在scroller函数中还是无法访问其firstChild属性?哪位大神给指点指点,谢谢了

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Scrolling Text</title>
    <style type="text/css">
        #div1 {
            background-color:darkgreen;
            color:white;
            font-family:'Courier New';
            font-weight:bold;
            position:absolute;
            border-style:groove;
            border-color:white;
            padding-left:10px;
            top:20px;
            left:10px;
            width:595px;
            height:6%;
            overflow:hidden;
        }
        img{
            position:absolute;
            top:10px;
            left:60px;
            border-style:solid;
        }
        body{
            background-color:#669966;
        }
    </style>
    <script type="text/javascript">
        var scroll_speed = 200;
        var chars = 1;
        var divElement;
        window.onload = function () {
            divElement = document.getElementById( "div1" );           
        }
        function scroller() {
            window.setTimeout( "scroller()", scroll_speed );
            var msg = divElement.firstChild.nodeValue;
            divElement.firstchild.nodeValue = msg.substring( chars ) + msg.substring( 0, chars );
        }
        scroller();
    </script>
</head>
<body>
    <img src="../images/img1.png" width="450" height="500" />
    <div id="div1">
        The latest new from Baghdad is not good tonight. Sand and rain are hindering our troops. The number of refugees continues to increase in the north...
    </div>
</body>
</html>

TPrime.A的主页 TPrime.A | 菜鸟二级 | 园豆:216
提问于:2013-11-18 19:44
< >
分享
最佳答案
0

很不幸,你的divElement在scroller执行后才被赋值。

onload是事件,给onload赋的值是事件触发后才执行的函数。

记住以下原则:

1、浏览器先解析head,并执行head里面的script标签里面的代码,并阻塞页面解析。

2、head解析完后开始解析body,并执行body里面的script标签里面的代码。

3、body解析完成后会触发onload事件。

根据以上,你的head里面的script标签里面的代码:

window.onload = function () {
    divElement = document.getElementById( "div1" );            
}

只是给onload绑定了一个事件处理函数,要等load事件触发时才会执行。

奖励园豆:5
Shine Ss | 菜鸟二级 |园豆:214 | 2013-11-18 20:32

没明白,我才刚开始学,能不能详细解释一下,或者说明如下如何修改?@Shine Ss

TPrime.A | 园豆:216 (菜鸟二级) | 2013-11-18 20:53

@hf_ttt: 修改了答案,看看这回明白了吗

Shine Ss | 园豆:214 (菜鸟二级) | 2013-11-18 21:33

@Shine Ss: 明白了,谢了。

TPrime.A | 园豆:216 (菜鸟二级) | 2013-11-18 21:47
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册