// 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();
// });
Правильная загрузка кавычек, нажатие на кнопку совместного доступа щебет генерирует правильный шаблон шаблона. Однако, в первый раз, нажав кнопку "Следующая цитата", ее нужно дважды щелкнуть, чтобы перейти к следующей цитате. После этого это всего лишь один клик. Любая помощь приветствуется.
Однако, в первый раз, нажав кнопку "Следующая цитата", ее нужно дважды щелкнуть, чтобы перейти к следующей цитате.
Это потому, что вы обновляете myIndex
в конце функции nextElement()
.
Вы должны сделать это как первый шаг
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;
};