TypeError: getElementById is null

后端 未结 4 1397
野性不改
野性不改 2020-12-22 14:05

    
        

        
相关标签:
4条回答
  • 2020-12-22 14:27

    Browsers run JavaScript as soon as possible in order to speed up rendering. So when you receive this code:

    <html>
        <head>
            <script type="text/javascript">
                var image = document.getElementById(image); // Missing quotes, typo?
    

    ... in runs intermediately. There's no <foo id="image"> on page yet, so you get null. Finally, you get the rest of the page rendered, including:

    <img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
    

    It's too late for your code, which finished running long ago.

    You need to bind a window.onload even handler and run your code when the DOM is ready (or move all JavaScript to page bottom, after the picture).

    0 讨论(0)
  • 2020-12-22 14:42

    You are executing javascript before your 'body' rendered. Thus document.getElementById("submit") would return null. Because there are no "submit" DOM element yet.

    One solution is to move your javascripts under 'body', Or use JQuery with

    $(document).ready(function() {
        ...
    });
    

    Your variable also has scope problem, your function cannot access variable declared outside this function with 'var' declaration. If you really need that variable, you should remove 'var' declaration. A better way is to move all your variable inside clicked function. like following code

    <html>
        <head>
        </head>
    <body>
        <div><h2>Project |</h2><h2> | herbykit</h2></div>
        <div>
            <button id="submit">Next</button><br/>
            <img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
            <p id="desc">first desc.</p>
       </div>
    
    
    </body>
    <script type="text/javascript">            
                function clicked(){
                    var image = document.getElementById("image");
                    var desc = document.getElementById("desc");    
                    var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiE.jpg"];   
                    var descs = ["1", "2"];
                    var num = 0;
                    var total = images.length;     
                    num = num + 1;
                    if (num > total){
                        num = 0;
                    }
                    image.src = images[num];
                    desc.innerHTML = images[num];
                }
                document.getElementById("submit").onclick = clicked;
            </script>
    </html>
    
    0 讨论(0)
  • 2020-12-22 14:45

    It should be document.getElementById('submit').onclick(clicked());

    0 讨论(0)
  • 2020-12-22 14:49

    your must enclose the id you are searching for in quotes:

    document.getElementById('ID_to_look_up');
    
    0 讨论(0)
提交回复
热议问题