gpt4 book ai didi

javascript - 使 onclick 与数组一起使用

转载 作者:行者123 更新时间:2023-12-03 02:57:40 25 4
gpt4 key购买 nike

我正在尝试为类制作一个简单的脚本。我已经弄清楚如何分别执行 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com