我在 JS 中创建了一个随机生成 GIF 的按钮, 我想通过让它们按顺序出现然后重复来改变这一点。
window.onload = () => {
const factsArr = [
{
image:'https://media.giphy.com/media/P6lX0T2MzYpdC/giphy.gif',
},
{
image:'https://media.giphy.com/media/uWdVKl2xN1eVi/giphy.gif',
},
{
image:'https://media.giphy.com/media/1nkUav308CBws/giphy.gif',
}
];
document.getElementById('generate-btn').addEventListener('click', () => {
const idx = Math.floor(Math.random() * factsArr.length);
document.getElementById('image').setAttribute('src', factsArr[idx].image)
})
}
<button id="generate-btn">Amazing Fact Button</button>
<img id="image"></img>
最佳答案
在下面的代码片段中,我使用了一个全局 currImage
变量,该变量在每次点击时都会增加,并在达到图像数组大小时重置。该图像取自数组的 currImage
索引。
// Init the variable
var currImage = 0;
window.onload = () => {
const factsArr = [
{ image:'https://media.giphy.com/media/P6lX0T2MzYpdC/giphy.gif'},
{ image:'https://media.giphy.com/media/uWdVKl2xN1eVi/giphy.gif'},
{ image:'https://media.giphy.com/media/1nkUav308CBws/giphy.gif'}
];
document.getElementById('generate-btn').addEventListener('click', () =>
{
document.getElementById('image').setAttribute('src', factsArr[currImage].image);
// increment the variable on each click
currImage++;
//reset the variable when it reaches the image array size
if (currImage == factsArr.length)
currImage = 0;
})
}
<button id="generate-btn">Amazing Fact Button</button>
<img id="image"></img>
关于按顺序生成对象的 JavaScript 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45784501/