2016-08-05 246 views
-1

是否可以遍歷此數組並逐個返回數組中的HTML引號 - 在每次按下按鈕之後?循環遍歷循環並返回數組中的字符串

這是我的一段代碼我想不通:

var quotes = ['"Time you enjoy wasting is not wasted time."', 
'"You can have it all. Just not all at once."', 
'"They say I am old-fashioned, and live in the past, but sometimes I think 
progress progresses too fast!"']; 

document.getElementById("btn1").addEventListener("click", newQuote); 
function newQuote(){ 
    for (var i = 0; i < quotes.length; i++) { 
    document.getElementById("quote").innerHTML = quotes[i]; 
    } 
} 

回答

0
var quotes = ['"Time you enjoy wasting is not wasted time."', 
'"You can have it all. Just not all at once."', 
'"They say I am old-fashioned, and live in the past, but sometimes I think 
progress progresses too fast!"']; 

var quoteNumber = 0; 
document.getElementById("btn1").addEventListener("click", newQuote); 
function newQuote(){ 
    document.getElementById("quote").innerHTML = quotes[quoteNumber]; 
    quoteNumber++; 
    if(quoteNumber == quotes.length) quoteNumber = 0; 
} 
+0

比k你的答案! – NJV

1

使用一個計數器來追蹤下一個報價的指數,並繞到它一旦你已經達到了最後一個:

var nextQuote = 0; 
 

 
var quotes = [ 
 
    '"Time you enjoy wasting is not wasted time."', 
 
    '"You can have it all. Just not all at once."', 
 
    '"They say I am old-fashioned, and live in the past, but sometimes I think progress progresses too fast!"' 
 
]; 
 

 
function newQuote() { 
 
    document.getElementById("quote").innerHTML = quotes[nextQuote]; 
 
    nextQuote = (nextQuote + 1) % quotes.length; 
 

 
}
<div id='quote'></div> 
 
<button onClick='newQuote()'>Next Quote</button>

+0

謝謝你的回答! – NJV