<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里面? 谢谢啦
window.onload=function(){};
</script>
写在这里的。
下面只是调用而已,
而且JSP的代码执行顺序是从上往下的
$(document).ready(function(){
//js代码
});
也就是说
document.getElementById('testDiv').appendChild(select);
在执行的时候
<div id="testDiv"></div> 还没有加载所以
document.getElementById('testDiv') == undefined
undefined后面在点方法肯定会报错。