// Quote Data
const data = {
quotes: [{
id: 1,
"author": "Shakespeare",
"source": "Julius Caesar",
"quote": "Cowards die many times before their deaths. The valiant never taste of death but once."
},{
id: 2,
"author": "Steinbeck",
"source": "East of Eden",
"quote": "And this I believe: that the free, exploring mind of the individual human is the most valuable thing in the world."
},{
id: 3,
"author": "Vonnegut",
"source": "Galápagos",
"quote": "..you are descended from a long line of determined, resourceful, microscopic tadpoles-- champions every one."
}]
};
var myIndex = 0;
var author = document.getElementById('author');
var source = document.getElementById('source');
var quote = document.getElementById('quote');
//Print first value of array right away.
author.innerHTML = data.quotes[myIndex].author;
source.innerHTML = data.quotes[myIndex].source;
quote.innerHTML = data.quotes[myIndex].quote;
//Generate Tweet with Quote Contents
function updateTweetURL() {
var shareQuote = document.getElementById('shareQuote');
shareQuote.href = 'https://twitter.com/intent/tweet?text=' + data.quotes[myIndex].quote + ' - ' + data.quotes[myIndex].author ;
}
updateTweetURL();
// Action when 'Next Quote' is clicked
document.getElementById('button').addEventListener("click", function() {
//Load next Quote
function nextElement() {
updateTweetURL();
author.innerHTML = data.quotes[myIndex].author;
source.innerHTML = data.quotes[myIndex].source;
quote.innerHTML = data.quotes[myIndex].quote;
myIndex = (myIndex+1)%(data.quotes.length);
};
nextElement();
});
// Action when Twitter Share is clicked
// document.getElementById('shareQuote').addEventListener("click", function() {
// //Generate Tweet with Quote Contents
// function updateTweetURL() {
// var shareQuote = document.getElementById('shareQuote');
// shareQuote.href = 'https://twitter.com/intent/tweet?text=' + data.quotes[myIndex].quote + ' - ' + data.quotes[myIndex].author ;
// }
// updateTweetURL();
// });
报价正确加载,单击 Twitter 共享按钮会生成正确的共享模板。然而,第一次单击“下一个报价”按钮时,必须单击两次才能到达下一个报价。此后,只需单击一下即可。如有任何帮助,我们将不胜感激。
最佳答案
However, on the very first time clicking on the "Next Quote" button, it has to be clicked twice to get to the next quote.
这是因为您要在函数 nextElement()
末尾更新 myIndex
。
你应该这样做作为第一步
function nextElement() {
myIndex = (myIndex+1)%(data.quotes.length); // <----------
updateTweetURL();
author.innerHTML = data.quotes[myIndex].author;
source.innerHTML = data.quotes[myIndex].source;
quote.innerHTML = data.quotes[myIndex].quote;
};
关于javascript - 为什么它需要最初双击才能运行功能,然后单击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44504125/