如何将数组中的第一个变量设为默认值

how can I make the first var in a array the default

本文关键字:变量 默认值 第一个 数组      更新时间:2023-09-26

我有一个使用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的值。

<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];
}

JS Fiddle Demo

你唯一的问题是语法错误。在getElementById("txtbox ")中有一个额外的空格,在textarea的样式声明中缺少引号,否则代码使用:

工作:
document.getElementById("txtbox").value = aquote[rdmQuote];
http://jsfiddle.net/CkaMW/