我创建了一个JavaScript按钮,按顺序从GIFs
生成giphy.com
,
我试图添加一个"了解更多"单击按钮时显示GIF
的文本
但显然按钮不再起作用了。
这是代码:
var currImage = 0;
window.onload = () => {
const factsArr = [
{ image:'https://media.giphy.com/media/3o7aD5tv1ogNBtDhDi/giphy.gif', source:"Know more" },
{ image:'https://media.giphy.com/media/3ohhwJax6g4Y8BK30k/giphy.gif', source:"know more" },
{ image:'https://media.giphy.com/media/1nkUav308CBws/giphy.gif', source="Know more" },
];
document.getElementById('source').addEventListener('click', () => {
document.getElementById('generate-btn').addEventListener('click', () => {
document.getElementById('image').setAttribute('src', factsArr[currImage].image);
currImage++;
if (currImage == factsArr.length)
currImage = 0;
})
}

<button id="generate-btn">Amazing Fact Button</button>
<img id="image"></img>
<div id="source"></div>
&#13;
答案 0 :(得分:1)
修复一些语法和逻辑错误后,代码可以正常工作。请参阅代码中的注释。
var currImage = 0;
window.onload = () => {
const factsArr = [
{ image:'https://media.giphy.com/media/3o7aD5tv1ogNBtDhDi/giphy.gif', source:"Know more" },
{ image:'https://media.giphy.com/media/3ohhwJax6g4Y8BK30k/giphy.gif', source:"know more" },
//{ image:'https://media.giphy.com/media/1nkUav308CBws/giphy.gif', source="Know more" }, syntax error "="
{ image:'https://media.giphy.com/media/1nkUav308CBws/giphy.gif', source:"Know more" },
];
//document.getElementById('source').addEventListener('click', () => {
//syntax error. arg list not closed
//logical error. nothing to click on window.onload. next lines never executed
/*
document.getElementById('generate-btn').addEventListener('click', () => {
document.getElementById('image').setAttribute('src', factsArr[currImage].image);
currImage++;
if (currImage == factsArr.length)
currImage = 0;
})
*/
//corrected code
const swtch = () => {
document.getElementById('image').setAttribute('src', factsArr[currImage].image);
document.getElementById('source').innerHTML=factsArr[currImage].source;
currImage++;
if (currImage == factsArr.length)
currImage = 0;
console.log(currImage);
};
document.getElementById('generate-btn').addEventListener('click', swtch);
document.getElementById('source').addEventListener('click', swtch);
}
<button id="generate-btn">Amazing Fact Button</button>
<div id="source"></div>
<img id="image" /><!--</img> img is self-closing-->