为什么它需要初始双击运行功能,然后单击?

时间:2017-06-12 16:15:52

标签: javascript addeventlistener

// 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();
// });

正确加载报价,点击“推特分享”按钮可生成正确的共享模板。但是,在第一次点击" Next Quote"按钮,必须单击两次才能进入下一个报价。此后,只需点击一下。任何帮助表示赞赏。

CodePen

1 个答案:

答案 0 :(得分:1)

However, on the very first time clicking on the "Next Quote" button, it has to be clicked twice to get to the next quote.

That's because you're updating myIndex at the end of the function nextElement().

You should do that as first step

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;
};