提问人:River Yoo 提问时间:12/19/2021 最后编辑:kiner_shahRiver Yoo 更新时间:12/19/2021 访问量:266
如何创建随机报价生成器?
How to create a randomized quote generator?
问:
我正在构建一个积极的肯定生成器,并希望得到一些输入。我正在尝试弄清楚如何生成报价。我已经写下了Math.random。下面是一些代码。
function newQuote() {
var randomNumber = Math.floor(Math.random() * (positiveAff.length));
document.getElementById(affirmations).innerHTML = positiveAff[randomNumber];
}
<body>
<h1>Positive Affirmations Generator</h1>
<div id="affirmations">
</div>
<button onclick="newQuote()">Click to change affirmations</button>
<script src="script.js"></script>
</body>
答:
1赞
Bimal Pariyar
12/19/2021
#1
我的答案是假设您将有一组引号。
const positiveAff = [
{ id: 1, quote: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit, dolores!" },
{ id: 2, quote: "consectetur adipisicing elit. Velit, dolores!" },
{ id: 3, quote: "amet consectetur adipisicing elit. Velit, dolores!" }]
const button = document.getElementById('button')
button.addEventListener("click", function () {
newQuote()
})
function newQuote() {
var randomNumber = Math.floor(Math.random() * (positiveAff.length));
document.getElementById("affirmations").innerHTML = positiveAff[randomNumber].quote;
}
<h1>Positive Affirmations Generator</h1>
<div id="affirmations"></div>
<button id="button">Click to change affirmations</button>
1赞
Dennis van de Hoef - Xiotin
12/19/2021
#2
根据您的代码片段,问题不在于您获取报价的代码。问题是你是怎么写的。在 use 中,作为变量,该变量从未定义过。我把它改成一个字符串,并添加了一个数组,现在它可以工作了。document.getElementById(affirmations)
affirmations
positiveAff = [
"Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit, dolores!",
"consectetur adipisicing elit. Velit, dolores!",
"amet consectetur adipisicing elit. Velit, dolores!"
]
function newQuote() {
var randomNumber = Math.floor(Math.random() * (positiveAff.length));
document.getElementById('affirmations').innerHTML = positiveAff[randomNumber];
}
<h1>Positive Affirmations Generator</h1>
<div id="affirmations"></div>
<button onclick="newQuote()">Click to change affirmations</button>
评论
positiveAff