日期:2014-05-16  浏览次数:20220 次

一个全局变量不起作用
[code=JScript][/code]
window.onload=initForm;
var a=document.getElementById("newLocation");
function initForm()
{
a.selectedIndex=0;//让页面返回时默认选择为第一个option
a.onchange=goPage;
}

function goPage()
{
var a=document.getElementById("newLocation");
var b=a.options[a.selectedIndex].value;
if(b!="")
{
window.location=b;
}
}

[code=HTML][/code]
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>select navigation</title>
<script src="js/select navigation.js"></script>
</head>
<body>
<form action="">
<select id="newLocation">
<option>友情链接</option><!--有了document.getElementById("newLocation").selectedIndex=0;-->
<option value="http://www.baidu.com">百度</option>
<option value="http://www.google.hk">谷歌</option>
<option value="http://www.qq.com">腾讯</option>
<option value="http://www.sohu.com">搜狐</option>
</select>
</form>
</body>
</html>

------解决方案--------------------
var a=document.getElementById("newLocation");
这句话是在页面加载的时候就执行了,但是这个时候页面还为加载完毕,还没有newLocation这个id的元素,所以,如果你想得到这个值,得在页面加载完毕后,给a赋值