2017-06-12 7 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共有ボタンをクリックすると正しい共有テンプレートが生成されます。ただし、最初の「次の見積もり」ボタンをクリックすると、次の見積もりに行くためには2回クリックする必要があります。その後は1回のクリックだけです。どんな助けもありがとうございます。なぜ機能を実行するには最初のダブルクリックが必要ですか?

CodePen

+0

VAR myIndex = 1 ... Youreのは、すでに負荷時には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

関連する問題