如何存储来自变量的静态值,保持在Javascript中的更改 [英] How to store static value from variable that keep changes in Javascript
问题描述
我创建了一个函数,它提供当前UTC日期和时间:
I have created a function that gives current UTC date and time:
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());
已调用到另一个函数中:
that has been called into another function :
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函数被调用到一个切换按钮。
And this on_timer function is called into a toggle button.
this.$el.find(".pt_timer_button button").on("click", this.on_timer);
问题:
每次按下开始按钮时,都会从 current_date 中获取新值。
我的条件是,如果按钮按下第一次比从current_date取FRESH值,如果页面被刷新,按钮再次按下,那么应该采取该FIRST值。 (它不应该采取另一个新的值)。
On each time when i press start button it takes new value from current_date. And my condition is, if button is pressed for 1st time than take FRESH value from current_date, And if page is refreshed and button is again pressed then it should take that FIRST value. (It should not take another fresh value).
所以有任何方法存储current_date的第一个值到另一个变量X,并让它保持静态。
So is there any way to store first value of current_date into some another variable X, and let it keep static. Or may I use cookies?
提前感谢。
推荐答案
这个代码演示了你需要的基本功能(我只使用你的代码的一部分)...
This code demonstrates the basic functionality you need (I only used part of your code)...
<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>
这篇关于如何存储来自变量的静态值,保持在Javascript中的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!