开发者

why change DOM property in anonymous function not working?

<html>
    <head>
        <title>test</title>
        <script type="text/javascript">
            function start(){
                document.getElementById("first_div").onclick = function(){
                    document.getElementById("another_div").style.color = "red";                 
                };
            }
        </script>   
    </head>
    <body onload="start()">
        <div id="first_div">first</div>
        <div id="anoter_div">second</div>
    </body>
</html>

when I click on the first_div, an error occurred:

TypeError: Result of expression 'document.getElementById("another_div")' [null] is not an object.

Any idea why this is not working?

th开发者_如何学运维ank you.


You've made a typo. Change:

document.getElementById("another_div")
                             ^

To:

document.getElementById("anoter_div")

Or you could change the name of your div, which is probably better:

<div id="anoter_div">second</div>

<div id="another_div">second</div>
             ^

The method document.getElementById(..) isn't able to find the element and returns null, which explains the error you're getting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜