我有與動態內容的div:檢查時間戳localStorage的記錄
<div id="news">test</div>
並希望添加其內容的localStorage 50秒,以防止對服務器的新的要求,如果是年齡超過50秒然後刪除它並設置一個新的內容。我jQuery是:
$(function(){
function now() {return+new Date}
var db = window.db = {
get : function(key) {
var entry = JSON.parse(localStorage.getItem(key)||"0");
if (!entry) return null;
if (entry.ttl && entry.ttl + entry.now < now()) {
localStorage.removeItem(key);
return null;
}
return entry.value;
},
set : function(key, value, ttl) {
localStorage.setItem(key, JSON.stringify({
ttl : ttl || 0,
now : now(),
value : value
}));
}
};
});
$(function() {
// Set Value with TTL of 50 Seconds using Milliseconds.
db.set("homeNews", $("#news").html(), 50000);
});
$(function() {
var contentsOfNews = db.get("homeNews");
$("#news").html(contentsOfNews);
});
的問題是:這是每個負荷增加的內容到localStorage的,但應該檢查時間戳,如果加入的含量大於50秒,然後重寫這個localStorage的數據。如果少於50秒,則不做任何事情。感謝您的幫助。
請隨意編輯小提琴:http://jsfiddle.net/KQmky/1/
萬分感謝
使用[setTimeout()](http://www.w3schools.com/jsref/met_win_settimeout.asp)函數 – Pavlo
謝謝帕夫洛,對不起,因爲愚蠢,但你能請幫助這在我的jsfiddle?謝謝 – qqruza
'''setTimeout(function(){db.set(「homeNews」,$(「#news」)。html(),50000);},50000);' – Pavlo