Javascript 如何将数组中的第一个变量设为默认值
我有一个使用onClick生成随机引号的脚本。然而,我需要的是一个特定的报价作为默认打开。之后,onclick将生成随机结果。以下是到目前为止我得到的信息:Javascript 如何将数组中的第一个变量设为默认值,javascript,random,Javascript,Random,我有一个使用onClick生成随机引号的脚本。然而,我需要的是一个特定的报价作为默认打开。之后,onclick将生成随机结果。以下是到目前为止我得到的信息: <button onClick="quotes()">ASK then CLICK</button> <br> <textarea id="txtbox" style="width:170px; readonly></textarea> <br> <br>
<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>
询问,然后单击
您唯一的问题是语法错误。您在getElementById(“txtbox”)
中有一个额外的空格,在textarea的样式声明中缺少一个引号,否则代码将使用:
document.getElementById("txtbox").value = aquote[rdmQuote];
您可以在HTML中显示默认文本,然后使用随机引号更改textarea的值
HTML
<textarea id="txtbox">This SHOULD ALWAYS APPEAR FIRST</textarea>
您可以像这样重新组织代码,并为随机报价或固定报价创建专用函数:
<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>
询问,然后单击
...
变量引号=[
“这应该总是先出现”,
“对此三思而后行”,
“省钱……”,
“房地产好”;
“参观岛屿”
];
函数randomQuote()
{
showQuote(Math.floor(Math.random()*quotes.length));
}
函数showQuote(索引){
document.getElementById(“txtbox”).value=quotes[index];
}
window.onload=函数(){
showQuote(0);
};
OP希望首先加载aNote[0]
,但此答案没有解决此问题。
<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>