2017-06-12 41 views
1
// 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分享按鈕會生成正確的共享模板。但是,在第一次點擊「下一個報價」按鈕時,必須點擊兩次以獲得下一個報價。此後,它只是一次點擊。任何幫助表示讚賞。爲什麼它需要初始雙擊運行功能,此後單擊?

CodePen

+0

VAR myIndex = 1 ...特殊照顧已經上載設定值0 ... –

回答

1

然而,在第一次點擊「下一步報價」按鈕,它必須被點擊兩次,以獲得下一個報價。

這是因爲您在功能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; 
}; 
+0

它總是小事情。謝謝! – lookininward