如何在Javascript中存储保持更改的变量的静态值

How to store static value from variable that keep changes in Javascript

本文关键字:变量 静态 Javascript 存储      更新时间:2023-09-26

我创建了一个函数,提供当前UTC日期和时间:

get_current_UTCDate: function() {
            var d = new Date();
            return d.getUTCFullYear() +"-"+ (d.getUTCMonth()+1) +"-"+d.getUTCDate()+" "+_.str.sprintf("%02d", d.getUTCHours())+":"+_.str.sprintf("%02d", d.getUTCMinutes())+":"+_.str.sprintf("%02d", d.getUTCSeconds());

被调用到另一个函数中:

on_timer: function(e) {
            var self = this;
            if ($(e.target).hasClass("pt_timer_start")) {
                current_date = this.get_current_UTCDate();    
                this.set_current_timer_activity({date: current_date});
                this.start_interval();
                }

这个on_timer函数被调用为一个切换按钮。

this.$el.find(".pt_timer_button button").on("click", this.on_timer);

问题:

每次按下启动按钮时,都会从current_date中获取新值。我的条件是,如果第一次按下按钮,则从current_date获取FRESH值,如果页面被刷新并再次按下按钮,那么它应该获取FIRST值。(不应采用其他新值)。

所以,有没有办法将current_date的第一个值存储到另一个变量X中,并使其保持静态。或者我可以用饼干吗?

提前谢谢。

这段代码演示了您需要的基本功能(我只使用了您的部分代码)。。。

<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
    obj = {
      get_current_UTCDate: function() {
        var d = new Date();
        return d.getUTCFullYear() +"-"+ (d.getUTCMonth()+1) +"-"+d.getUTCDate()+" "+ d.getUTCHours()+":"+ d.getUTCMinutes()+":"+ d.getUTCSeconds();
      },
      on_timer: function() {
        if (localStorage.getItem("curdate") == null) {
          localStorage.setItem("curdate",obj.get_current_UTCDate());
          alert('first time');
        }
        alert(localStorage.getItem("curdate"));
      }
    }
    $(document).ready(function(){
        $('button').on("click", obj.on_timer);
    });
    </script>
  </head>
  <body>
    <button>click</button>
  </body>
</html>  

在不了解所有需求的情况下,我会考虑使用cookie来存储值。既然你已经在使用jQuery了,你可以使用$cookie插件,或者只使用一个基本的set/get例程,比如:

function cookies() {
    return document.cookie.split('; ').reduce(function(acc, v) {
        p = v.split('='); acc[p[0]] = p[1]; return acc;
    }, {});
}
function getCookie(key) {
    return cookies()[key];
}
function setCookie(key, value) {
    return document.cookie = [key, '=', value, ';'].join('');
}

然后在你的代码中,类似于:

if ($(e.target).hasClass("pt_timer_start")) {
    if (saved_date = getCookie('current_date')) {
        current_date = saved_date;
    } else {
        current_date = this.get_current_UTCDate();
        setCookie('current_date', current_date);
    }    
    this.set_current_timer_activity({date: current_date});
    this.start_interval();
}