2011-09-18 79 views
0

的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的第一条语句)返回?

+1

诊断这种事情的常用方法是调试。使用'console.log'或'alert()'来测试输出,看看哪一点出了问题。这样,你也可以自己找出那个线返回的是你询问的内容 –

+0

@Pekkai曾经尝试过这种方法,但是不理解输出。它返回'object HTML select element'。我不明白这一点。 –

+0

如果你真的想*学习*如何做到这一点,那么也许会问一个关于这个问题。这将比有人找出当前脚本中的问题更有效率 –

回答

1

您可以尝试

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

声明

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

刚刚发现DOM(HTML)元素<... id="newLocation" ...>,即你的<select id="newLocation">

0

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

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

相关问题