-2

我有这个 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);
    }
  }
}

本地存储:

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');
}
}
}
4

1 回答 1

4

不要使用 cookie:它将在每次请求时发送到服务器。您可以改用本地存储

function load() {
  var eventsFired = localStorage.getItem('fired');

  if (eventsFired != '1'){
      doYourStuff();
      localStorage.setItem('fired', '1');
  }
}
于 2013-04-04T19:09:15.597 回答