如何将倒数计时器设置为Cookie过期日期?

时间:2016-01-13 18:14:32

标签: javascript jquery cookies timer

做一个Cookie过期日期倒计时器的好方法是什么? 我正在开发一个静态的html页面,我有问题找到如何实际做到这一点,这样的事情(jsfiddle)应该适合我需要的东西,问题出在设置秒数左边在设置cookie之后,不知道如何做到这一点。请注意,计时器和“设置cookie”将在不同的页面中。希望你能给我一些提示或想法。

JS小提琴代码:

<script>
    //count down function

var seconds_left = 10;
var interval = setInterval(function() {
    document.getElementById('timer_div').innerHTML = --seconds_left;

    if (seconds_left <= 0)
    {
       document.getElementById('timer_div').innerHTML = "You are Ready!";
       clearInterval(interval);
    }
}, 1000);

//set the cookie funcion

    function music_player(){
    days=1; // number of days to keep the cookie
    myDate = new Date();
    myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
    document.cookie = 'music_player=play; expires=' + myDate.toGMTString();
    }
</script>

<a href="#" class="yes_alive" onclick="music_player()">Set the cookie</a>
<div id="timer_div"></div>

1 个答案:

答案 0 :(得分:0)

我相信我已经知道你想要实现的目标。我做了一些更改,可以帮助您实现总体目标。当您单击链接时,倒计时器将根据您为Cookie过期设置的秒数启动。

实时预览:https://www.quora.com/What-are-the-ways-to-insert-an-image-path-into-the-MySQL-database-and-save-it-in-the-folder-and-display-the-same-image-in-a-web-page-via-PHP/answer/Gajus-Kuizinas

HTML:

 <div id='timer_div'></div>

<a href="#" id="yes_alive" >Set the cookie</a>
<div id="timer_div"></div>

JavaScript的:

//store the number of days
var days = 1;

//store the number of seconds
var seconds_left = days * 24 * 60 * 60 * 1000;

//register the  click event
document.getElementById("yes_alive").addEventListener("click", function(event) {

  //stop default action of the anchor tag
  event.preventDefault();

  //call the music player and set the cookie
  music_player(days);

  //start the count down timer
  startTimer(seconds_left);

});

function startTimer(seconds_left) {

  var interval = setInterval(function() {
    document.getElementById('timer_div').innerHTML = --seconds_left;

    if (seconds_left <= 0) {
      document.getElementById('timer_div').innerHTML = "You are Ready!";
      clearInterval(interval);
    }
  }, 1000);

}

function music_player(days) {

  myDate = new Date();
  myDate.setTime(myDate.getTime() + (days * 24 * 60 * 60 * 1000));
  document.cookie = 'music_player=play; expires=' + myDate.toGMTString();

}