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

자바 스크립트 : 내가 콤보 상자에서 옵션을 선택하면

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 함수의 첫 번째 문장) return?

+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.getSelectedIndexnewLoc.selectedIndex으로 변경해야합니다.

관련 문제