<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>HTML DOM创建元素本文</title>   
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2>下拉框</h2>
        <div id="testDiv"></div>
    </div>
     <script type="text/javascript">
    var select=document .createElement("select");
    select.options[0] = new Option("加载项1", "value1");
    select.options[1] = new Option("加载项2", "value2");
    select.options[2] = new Option("加载项3", "value3");
    select.options[3] = new Option("加载项4", "value4");
    select.size = "4";
    document.getElementById('testDiv').appendChild(select);
    </script>
    </form>
</body>
</html>为什么换成下面的却有错误:<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>HTML DOM创建元素本文</title>
  <script type="text/javascript">
    var select=document .createElement("select");
    select.options[0] = new Option("加载项1", "value1");
    select.options[1] = new Option("加载项2", "value2");
    select.options[2] = new Option("加载项3", "value3");
    select.options[3] = new Option("加载项4", "value4");
    select.size = "4";
    document.getElementById('testDiv').appendChild(select);
    </script>   
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2>下拉框</h2>
        <div id="testDiv"></div>
    </div>
    </form>
</body>
</html>为什么放在head里面不能正常执行呢  高手给我详细讲讲 还有什么情况下javascript代码不能放在head里面?  谢谢啦

解决方案 »

  1.   

    执行顺序是从上到下养成习惯,代码写在onload 中
    window.onload=function(){};
      

  2.   

    因为放到head里面,body里面的还没有加载,所以你的document.getElementById('testDiv')得到的为null,因此报错!
      

  3.   

    页面加载的顺序问题。放在head里面而又没有用window.onload包含时。此时页面还没形成div .因此document.getElementById('testDiv') 是获取不到内容的。
      

  4.   

    <script type="text/javascript">
    </script>
    写在这里的。
    下面只是调用而已,
    而且JSP的代码执行顺序是从上往下的
      

  5.   

    一般要在DOM元素加载完后执行js代码...这样不容易出现找不到元素的问题 代码都会放到这里  
    $(document).ready(function(){
       //js代码
    });
      

  6.   

    其实跟head是没有多大关系的,js是顺序下来的!而在那个id为testDiv之前,document.getElementById("testDiv");是得不到结果的!所以需要在div之后才能执行js脚本!或者用onload = “functionname()”在body里加载
      

  7.   

    就是加载顺序问题,如果放在head里写在window.onload=function (){ //代码写这里 }
      

  8.   

    这是因为在这个html还没有加载完的时候js已经执行了
    也就是说
    document.getElementById('testDiv').appendChild(select);
    在执行的时候
    <div id="testDiv"></div> 还没有加载所以
    document.getElementById('testDiv') == undefined 
    undefined后面在点方法肯定会报错。