Web ページに引用符を表示したいのですが、配列に 10 個の引用符があります。配列quotes[]
から任意の 1 つの引用符をランダムに選択して、1 秒ごとに変更したいと考えています。JavaScript のみを使用してこれを実行したいと考えています。
使っsetTimeout
たけど全部ダメ。誰でも私が使用できるダミーコードまたは機能を手伝ってくれますか?
Web ページに引用符を表示したいのですが、配列に 10 個の引用符があります。配列quotes[]
から任意の 1 つの引用符をランダムに選択して、1 秒ごとに変更したいと考えています。JavaScript のみを使用してこれを実行したいと考えています。
使っsetTimeout
たけど全部ダメ。誰でも私が使用できるダミーコードまたは機能を手伝ってくれますか?
を使用して、次のアプローチをお勧めしますwindow.setInterval()
。
var q = ['quote 1', 'quote 2', 'quote 3', 'pick your own note'];
function quoteChange (target, quotes) {
if (!quotes || !target) {
return false;
}
else {
var n = Math.floor(Math.random() * quotes.length),
text = 'textContent' in document ? 'textContent' : 'innerText'
target[text] = quotes[n];
}
}
var change = window.setInterval(function(){
quoteChange(document.getElementById('demo'), q);
}, 1000);
参考文献:
setInterval
の代わりに使用しsetTimeOut
ます。
以下のリンクに示されていることに従うと、魅力的に機能するはずです。
https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
これを使って :
setInterval ( ChangeText, 1000 ); //Function Name,Time to repeat this funcion
function ChangeText(){
var randNumber = Math.floor((Math.random()*10)+1);
var quote = quotes[randNumber];
var String = document.getElementById("LabelName");
String.innerHTML = quote;
}
もちろん、setInterval を使用することも、以下のように setTimeout を使用することもできます。
var quotes = ['first', 'second', 'third'];
function updateQuote(){
var selectedIndex = Math.floor(Math.random() * quotes.length);
container.innerText = quotes[selectedIndex];
setTimeout(updateQuote,1000);
}
updateQuote();
作業サンプルはこちら: http://plnkr.co/edit/?p=preview