2015-10-05 129 views
0

要調試的另一個代碼必須保持不變,因爲它不能重寫。但我想知道爲什麼newQuote吐出錯誤未定義。我也相信,我需要修復定時器設置,讓它顯示,因爲var tick沒有被調用,但不是100%肯定有任何建議,因爲我找不到任何錯誤超出newQuote undefinednewQuote未定義爲什麼

<!DOCTYPE html PUBLIC 
"-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html> 
<head> 
<meta charset="utf-8" /> 
<title>Random Proverbs</title> 
<script type="text/javascript"> 
<!-- HIDE FROM INCOMPATIBLE BROWSERS 
function changeQuote() { 
    quotes = new Array; 
    quotes[0] = "Laughter is the best medicine."; 
    quotes[1] = "Never look a gift horse in the mouth."; 
    quotes[2] = "One good turn deserves another."; 
    quotes[3] = "The early bird catches the worm."; 
    quotes[4] = "Two is company, three is a crowd."; 
    var newQuote = quotes[Math.round(Math.random()+quotes.length)]; 
    document.quoteform.quote.value = newQuote; 
} 
var tick = setInterval(changeQuote(), 1000); //missing time in milliseconds and double quotes not needed 
// STOP HIDING FROM INCOMPATIBLE BROWSERS --> 
</script> 
</head> 
<body> 
<form id="quoteform" action=""> <!--Was --> 
<input type="text" size="50" id="quote" name="quote" /><br /> 
</form> 
</body> 
</html> 
+0

'setInterval(changeQuote,1000)' – zerkms

+0

檢查你的隨機數發生器,你將會得到數組超出範圍 –

+0

它應該是數學。 random()* quotes.length – jollyjoyce1995

回答

1

變化document.quoteform.quote到document.forms.quoteform.quote 然後命名形式quoteform 所以新的JavaScript看起來像

function changeQuote() { 
    var quotes = new Array; //was var defintion 
    quotes[0] = "Laughter is the best medicine."; 
    quotes[1] = "Never look a gift horse in the mouth."; 
    quotes[2] = "One good turn deserves another."; 
    quotes[3] = "The early bird catches the worm."; 
    quotes[4] = "Two is company, three is a crowd."; 
    var newQuote = quotes[Math.floor(Math.random()*quotes.length)]; 
    document.forms.quoteform.quote.value = newQuote; 
} 
setInterval(changeQuote, 1000); 

那麼所有你需要的是改變ID在開始表單中標記名稱

0

您需要使用Math.floor避免數組的邊界之外去,改變+*由數組的長度乘以隨機數。

var newQuote = quotes[Math.floor(Math.random()*quotes.length)];