如何将数组中的第一个变量设为默认值
how can I make the first var in a array the default
我有一个使用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>
你可以像这样重新组织你的代码,并为随机引用或固定引用创建专用函数:
<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>
您可以在HTML中显示默认文本,然后使用随机引号更改textarea的值。