javascript - 使 onclick 与数组一起使用

标签 javascript arrays function onclick

我正在尝试为类制作一个简单的脚本。我已经弄清楚如何分别执行 onclick 事件和数组,但不确定如何使它们一起工作。我仍然希望命运在刷新时改变,但可以选择单击按钮。

点击:

<button onclick="myFunction()">Get your fortune!</button>
<p id="fortune"></p>

<script>
function myFunction() {
document.getElementById("fortune").innerHTML = ???? ;
}
</script> 

数组:

<script>
var fortune = new Array(10);
fortune[0]="May life throw you a pleasant curve.";
fortune[1]="Procrastination is the thief of time.";
fortune[2]="Your road to glory will be rocky, but fulfilling.";
fortune[3]="Patience is your alley at the moment. Don’t worry!";
fortune[4]="All things are difficult before they are easy.";
fortune[5]="If you want the rainbow, you have to tolerate the rain.";
fortune[6]="Determination is what you need now.";
fortune[7]="Do not let ambitions overshadow small success.";
fortune[8]="First think of what you want to do; then do what you have to do.";
fortune[9]="Hard words break no bones, fine words butter no parsnips."; 

c=Math.round(Math.random()*9);

document.write(fortune[c]);
</script>

最佳答案

有这样的事吗?还可以通过 addEventListener 函数添加事件监听器。

var fortunes = new Array(10);
fortunes[0]="May life throw you a pleasant curve.";
fortunes[1]="Procrastination is the thief of time.";
fortunes[2]="Your road to glory will be rocky, but fulfilling.";
fortunes[3]="Patience is your alley at the moment. Don’t worry!";
fortunes[4]="All things are difficult before they are easy.";
fortunes[5]="If you want the rainbow, you have to tolerate the rain.";
fortunes[6]="Determination is what you need now.";
fortunes[7]="Do not let ambitions overshadow small success.";
fortunes[8]="First think of what you want to do; then do what you have to do.";
fortunes[9]="Hard words break no bones, fine words butter no parsnips."; 

var fortune = document.getElementById("fortune");
var button = document.getElementById("button");

button.addEventListener('click', function () {
   var c = Math.round(Math.random() * 9);
   fortune.innerHTML = fortunes[c];
});
<button id="button">Get your fortune!</button>
<p id="fortune"></p>

关于javascript - 使 onclick 与数组一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47546276/

相关文章:

javascript - 如何打印 JavaScript 函数的原始字符串

javascript - Ajax XHR 返回 500 错误,但 PHP 文件可以工作

javascript - 谜题麻烦 - 试图保存初始棋盘

c - C语言中如何判断一个字符串是否为整数?

c++ - 如何将变量从 C++ 中的一个函数返回到 main,然后在另一个函数中使用它?

function - 使用 XQuery 扁平化 XML

javascript - SEO 友好的 javascript 和 CSS 链接?

javascript - 提高交错列等距网格上点击检测的性能

python - 传递给 `np.ones` 的参数是什么?它在这里如何工作?

c - 直方图,频率的计算