我有这个JavaScript函数,我需要只执行一次(满足某些条件时),然后让cookie记住它,而不是24小时再运行它。
我试过这个使用jquery.cookie.js插件的脚本,但它不起作用:
var eventsFired = ($.cookie('eventsFired') != null)
? $.cookie('eventsFired')
: 0;
function load() {
if (eventsFired == 0){
if (window.frames[0].document.getElementById('applications')) {
var str=document.getElementById("tst").innerHTML;
var n=str.replace("Login","Logout");
document.getElementById("tst").innerHTML=n;
document.getElementById('tst').title ='logout';
document.getElementById('tst').href='logout';
document.getElementById('prt').href='../profile/cont.html';
eventsFired++;
$.cookie('eventsFired', eventsFired);
}
}
}
Localstorage:
function load() {
var eventsFired = localStorage.getItem('fired');
if (eventsFired == '1'){
if (window.frames[0].document.getElementById('applications'))
{
var str=document.getElementById("tst").innerHTML;
var n=str.replace("Login","Logout");
document.getElementById("tst").innerHTML=n;
document.getElementById('common').href='..css/common2.css';
document.getElementById('tst').title ='logout';
document.getElementById('tst').href='logout';
document.getElementById('prt').href='../profil/cont.html';
localStorage.setItem('fired', '1');
}
}
}
答案 0 :(得分:3)
不要使用cookie:它会在每次请求时发送到服务器。您可以改为使用local storage:
function load() {
var eventsFired = localStorage.getItem('fired');
if (eventsFired != '1'){
doYourStuff();
localStorage.setItem('fired', '1');
}
}