为什么这个剧本不起作用......?

时间:2011-09-18 18:19:56

标签: javascript

html代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="script.js">
</script>
</head>

<body bgcolor="#FFFFCC">
<center>
<form>
 <select id="newLocation">
  <option value="1.jpg">index</option>
   <option value="script.js">posts</option>
   <option value="2.jpg" selected="selected">blog</option>
 </select>
</form>

javascript:

window.onload = startInit;

function startInit() {
document.getElementById("newLocation").selectedIndex = 0;
document.getElementById("newLocation").onchange = jumpPage;
}

function jumpPage() {
var newLoc = document.getElementById("newLocation");// what does this statement return ?
var newPage = newLoc.options[newLoc.getSelectedIndex].value;
if(newPage != "")
   window.location = newPage;
}

为什么不进入新页面,即从组合框中选择选项时的值? 另外document.getElementById("newLocation");这个语句(函数jumpPage的第一个语句)返回了什么?

2 个答案:

答案 0 :(得分:1)

你可以尝试

var newPage = newLoc.options[newLoc.selectedIndex].value;

声明

var newLoc = document.getElementById("newLocation"); 

只找到DOM(HTML)元素<... id="newLocation" ...>,即您的<select id="newLocation">

答案 1 :(得分:0)

document.getElementById("newLocation")会返回SELECT对象(即对下拉列表的引用)。

关于JS,它有一个错误。您应该将newLoc.getSelectedIndex更改为newLoc.selectedIndex