每小时显示另一个内容

时间:2014-05-19 12:15:22

标签: javascript arrays

我想每小时在我的网站上显示不同的内容,我发现了这个:

Fiddle

<button onClick="getPhrase()">Show me a phrase for this hour</button>
<div id="placeHolder"></div>
window.getPhrase = function() {
    h = new Date().getHours(); //Get the current hour

    phrase = new Array(); //Create an array of phrases
    phrase[1] = 'Hello';
    phrase[2] = 'there';
    phrase[3] = 'this';
    phrase[4] = 'will';
    phrase[5] = 'show';
    phrase[6] = 'a';
    phrase[7] = 'different';
    phrase[8] = 'message';
    phrase[9] = 'depending';
    phrase[10] = 'on';
    phrase[11] = 'the';
    phrase[12] = 'hour';
    phrase[13] = 'of';
    phrase[14] = 'day';
    phrase[15] = 'that';
    phrase[16] = 'you';
    phrase[17] = 'look';
    phrase[18] = 'at';
    phrase[19] = 'it';
    phrase[20] = '!';
    phrase[21] = 'W';
    phrase[22] = 'X';
    phrase[23] = 'Y';
    phrase[24] = 'Z';

    document.getElementById('placeHolder').innerHTML = phrase[h-1]; //Show the array item relevant to the hour
}

但是如何在没有按钮的情况下显示它? 如何删除按钮?

2 个答案:

答案 0 :(得分:0)

带有计时器。这将每秒刷新一次。

setInterval(function() {
    h = new Date().getHours(); //Get the current hour

    phrase = new Array(); //Create an array of phrases
    phrase[1] = 'Hello';
    phrase[2] = 'there';
    phrase[3] = 'this';
    phrase[4] = 'will';
    phrase[5] = 'show';
    phrase[6] = 'a';
    phrase[7] = 'different';
    phrase[8] = 'message';
    phrase[9] = 'depending';
    phrase[10] = 'on';
    phrase[11] = 'the';
    phrase[12] = 'hour';
    phrase[13] = 'of';
    phrase[14] = 'day';
    phrase[15] = 'that';
    phrase[16] = 'you';
    phrase[17] = 'look';
    phrase[18] = 'at';
    phrase[19] = 'it';
    phrase[20] = '!';
    phrase[21] = 'W';
    phrase[22] = 'X';
    phrase[23] = 'Y';
    phrase[24] = 'Z';

    document.getElementById('placeHolder').innerHTML = phrase[h-1]; //Show the array item relevant to the hour
}, 1000);

答案 1 :(得分:0)

这将在每小时后拨打 的的javascript

function getPhrase(){
    var h = new Date().getHours(); //Get the current hour
    var phrase = new Array(); //Create an array of phrases
    phrase = ['Hello', 'there', 'this', 'will', 'show', 'a', 'different', 'message', 'depending', 'on', 'the', 'hour', 'of', 'day', 'that', 'you', 'look', 'at', 'it', '!', 'W', 'X', 'Y', 'Z'];
    document.getElementById('placeHolder').innerHTML = phrase[h-1]; //Show the array item relevant to the hour
}

setInterval(getPhrase,60*60*1000);

删除按钮

<强> HTML

<div id="placeHolder"></div>