newQuote未定义为什么

问题描述:

要调试的另一个代码必须保持不变,因为它不能重写。但我想知道为什么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

变化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在开始表单中标记名称

您需要使用Math.floor避免数组的边界之外去,改变+*由数组的长度乘以随机数。

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