javascript code not work in HEAD tag

我是研究僧i 提交于 2019-11-26 11:39:36

问题


My webpage has the following code:

<html>
<head>
    <title>This is test Page</title>

     <script language=\"javascript\" type=\"text/javascript\">

         document.getElementById(\"msg1\").innerHTML = document.URL.toString();
        </script>

</head>
<body>

    <div class=\"sss\">
        <p id=\"msg1\"></p>
    </div>


</body>
</html>

As you now at the time the script executes the div doesn\'t exist but I want to put my JavaScript code only In the <head> tag and I won\'t put it in middle of HTML code.

But this code only works when I put the <script> tag after the <div> tag. I use VS2010 and firefox 19.0.1

Is there anyway to put code in <head> tag?


回答1:


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>



回答2:


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
}



回答3:


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.




回答4:


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>



回答5:


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();


来源:https://stackoverflow.com/questions/15675745/javascript-code-not-work-in-head-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!