2011-09-18 80 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

相關問題