javascript code not work in HEAD tag

后端 未结 6 1452
有刺的猬
有刺的猬 2020-11-29 13:18

My webpage has the following code:



    This is test Page

     

        
相关标签:
6条回答
  • 2020-11-29 14:00

    Your script uses dom element and must run after the dom loaded.

    Wrap your code in a function and call it after dom loaded

    function myfunc(){  
    //code here
    }
    window.onload = myfunc();
    
    0 讨论(0)
  • 2020-11-29 14:05

    Michael Geary is right, in order to execute your code, I'd use jQuery library (a de-facto standard in JS development) and utilize the DOM ready event. This will ensure the code in the handler will execute once DOM is fully loaded.

    <script>
      $(function(){
        $('#msg1').html(document.URL.toString());
      });
    </script>
    
    0 讨论(0)
  • 2020-11-29 14:13

    I recommend to to use addEventListener like this:

    <script language="javascript" type="text/javascript"> 
    document.addEventListener("DOMContentLoaded",() => { 
           document.getElementById("msg1").innerHTML = document.URL.toString();
        });
    </script>
    
    0 讨论(0)
  • 2020-11-29 14:19

    Your script relies on the DOM being ready, so you need to execute that function call only after the DOM is ready.

    <script language="javascript" type="text/javascript">
    
    window.onload = function() {
        document.getElementById("msg1").innerHTML = document.URL.toString();
    }
    
    </script>
    
    0 讨论(0)
  • 2020-11-29 14:19

    Your script uses a DOM element and therefore must run after the DOM is loaded. You can do that by using this function:

    $(document).ready(function(){
        //code here
    }
    
    0 讨论(0)
  • 2020-11-29 14:20

    The various tags in your HTML page are loaded and processed in the order in which they appear on the page. Your <script> tag is executed immediately when it is parsed in the <head>. This is before the <body> and the elements inside the <body> are parsed. So, the script tries to reference an element that is not defined at the time it is executed.

    0 讨论(0)
提交回复
热议问题