另一个为我调试的代码必须保持与无法重写相同的代码。但我想知道为什么newQuote吐出错误未定义。我还认为我需要修复计时器设置才能显示,因为var tick没有被调用,但不是100%确定有任何建议值得赞赏,因为我找不到任何超出newQuote undefined的错误
<!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 :(得分: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更改为name
答案 1 :(得分:0)
您需要使用Math.floor来避免超出数组的范围,并将 + 更改为 * 以将随机数乘以数字的长度阵列。
var newQuote = quotes[Math.floor(Math.random()*quotes.length)];