如何在Javascript中存储保持更改的变量的静态值
How to store static value from variable that keep changes in Javascript
我创建了一个函数,提供当前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();
}
相关文章:
- Node.js-模块导出静态变量
- 使用变量而不是静态字符串搜索数组
- 在angularJS中定义函数内部的静态变量
- jsp内部html中的Javascript静态变量
- 创建静态(类)变量-最佳实践
- 是否可以在window.onresize上更改jQuery插件的静态变量
- 如何使用 dedeclare 定义 dojo 静态变量或静态对象
- 为什么我可以在ServiceNow中访问示例脚本化Web服务(订购黑莓)并返回静态变量,但它没有订购黑莓
- 为什么 Object.create 使我的私有变量成为静态变量
- 使用静态变量初始化同一类中的变量
- 具有 John Resig 简单类模式的静态变量
- 使用原型模拟静态变量
- 如何在 javascript 中使用 const 关键字 (ecma 6) 和函数静态变量
- 为什么要在函数定义之外引用静态变量(函数属性)
- 设置超时函数回调静态变量
- 使用 get 变量缓存静态 HTML 页面
- Javascript 类中的静态变量
- 更新 JavaScript 函数中的静态变量
- 一个静态 php 变量,只分配一次,永远不会更改
- Javascript - 使用闭包递增静态函数变量模拟