开发者

javascript loading problem

When i am trying to write the co开发者_运维知识库de like document.getElementById('id1') after teh script tag it is showing document.getElementById(..) null or not an object.. Is it necessary to write document.getElementById('id1') in function only. If i write this code in function then it is accepting. So what the mistake here.. and if i want to execute a function on loading of the page where to write onLoad() function.. i try to write at but it is not loading.. please help me Thank you


In order to be sure that your dom element is loaded, you have to wait the document is loaded.

To do this you can do:

<head>

    <script type="text/javascript">
        function foo(){
          var elem = document.getElementById("yourElem");
        //...
        }
    </script>
</head>
<body onload="foo()">...</body>

or

<head>

    <script type="text/javascript">
        function foo(){
         var elem = document.getElementById("yourElem");
        //...
        }

        window.onload = foo;
    </script>
</head>
<body>...</body>


If you want the script to run after the page is loaded, you can use window.onload.

<script>
window.onload = function () {
    //code goes here
}
.
.
.
</script>


Put your script bellow the element you are getting will also work.

<div id="ele"></div>
<script language="javascript">
    alert(document.getElementById('ele').tagName);
</script>
<div id="ele1"></div>

But unless you have special purpose, it's a good habit to write handlers in after document loaded, that is, put your code in window.onload event handler.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜