我有一个使用onClick生成随机引号的脚本。但是,我需要的是将特定报价作为默认值打开。之后,onClicks应该产生随机结果。这是我到目前为止所得到的:
<button onClick="quotes()">ASK then CLICK</button>
<br>
<textarea id="txtbox" style="width:170px; readonly></textarea>
<br>
<br>
<script>
function quotes() {
var aquote = new Array;
aquote[0] = " This SHOULD ALWAYS APPEAR FIRST ";
aquote[1] = "Think twice about this ";
aquote[2] = "Save your money.... ";
aquote[3] = "Real Estate is good ";
aquote[4] = "Visit the Islands "
rdmQuote = Math.floor(Math.random() * aquote.length);
document.getElementById("txtbox ").value = aquote[rdmQuote];
}
window.onload = quotes;
</script>
答案 0 :(得分:1)
您可以像这样重新组织代码,并为随机引用或固定引用创建专用函数:
<button onClick="randomQuote()">ASK then CLICK</button>
...
<script>
var quotes = [
" This SHOULD ALWAYS APPEAR FIRST ",
"Think twice about this ",
"Save your money.... ",
"Real Estate is good ";
"Visit the Islands "
];
function randomQuote()
{
showQuote(Math.floor(Math.random() * quotes.length));
}
function showQuote(index) {
document.getElementById("txtbox ").value = quotes[index];
}
window.onload = function() {
showQuote(0);
};
</script>
答案 1 :(得分:0)
你唯一的问题是语法错误。您在getElementById("txtbox ")
中有一个额外的空格,并且textarea的样式声明中缺少引号,否则代码可以使用:
document.getElementById("txtbox").value = aquote[rdmQuote];
答案 2 :(得分:0)
您可以在HTML中显示默认文本,然后使用随机引号更改textarea的值。
<强> HTML 强>
<textarea id="txtbox">This SHOULD ALWAYS APPEAR FIRST</textarea>
<强> JS 强>
var aquote = [
"Think twice about this ",
"Save your money.... ",
"Real Estate is good ",
"Visit the Islands "
];
var random = -1;
function quotes() {
var temp = random;
// Make sure we do not display the same quote twice in a row
while(temp == random) temp = Math.floor(Math.random() * aquote.length);
random = temp;
document.getElementById("txtbox").innerHTML = aquote[random];
}