我有一个字符串&单击JS按钮时显示的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/TvsLe5DV4gKCQ/giphy.gif',
source: "know more"
},
{
image: 'https://media.giphy.com/media/1nkUav308CBws/giphy.gif',
source: "know more"
},
];
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" />
我想将链接添加到“了解更多”。
答案 0 :(得分:0)
将HTML放入源
var currImage = 0;
window.onload = () => {
const factsArr = [
{ image:'https://media.giphy.com/media/3o7aD5tv1ogNBtDhDi/giphy.gif', source:"<a href='https://www.example.com'>know more 1</a>" },
{ image:'https://media.giphy.com/media/TvsLe5DV4gKCQ/giphy.gif', source:"<a href='https://www.example.com'>know more 2</a>" },
{ image:'https://media.giphy.com/media/1nkUav308CBws/giphy.gif', source:"<a href='https://www.example.com'>know more 3</a>" },
];
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);
}
&#13;
<button id="generate-btn">Amazing Fact Button</button>
<div id="source"></div>
<img id="image" />
&#13;
或添加新属性并更改您的html
var currImage = 0;
window.onload = () => {
const factsArr = [
{ image:'https://media.giphy.com/media/3o7aD5tv1ogNBtDhDi/giphy.gif', source:"know more", href: "https://www.example.com" },
{ image:'https://media.giphy.com/media/TvsLe5DV4gKCQ/giphy.gif', source:"know more", href: "https://www.example.com" },
{ image:'https://media.giphy.com/media/1nkUav308CBws/giphy.gif', source:"know more", href: "https://www.example.com" },
];
const swtch = () => {
document.getElementById('image').setAttribute('src', factsArr[currImage].image);
const out = document.getElementById('source');
out.innerHTML=factsArr[currImage].source;
out.href=factsArr[currImage].href;
currImage++;
if (currImage == factsArr.length)
currImage = 0;
console.log(currImage);
};
document.getElementById('generate-btn').addEventListener('click', swtch);
document.getElementById('source').addEventListener('click', swtch);
}
&#13;
<button id="generate-btn">Amazing Fact Button</button>
<div><a id="source"></a></div>
<img id="image" />
&#13;