如何使用JavaScript / jQuery仅在页面首次加载时显示消息框


How do I show a message box only the first time a page loads, using JavaScript / jQuery?

我想显示一个消息框,仅在网页第一次加载时显示。如果用户刷新,它应该不再显示。无论用户是否已登录,都应显示该消息。

cookie 是执行此操作的唯一方法,还是有任何 JavaScript 库可以采用这种方法?技术堆栈是jQuery/JavaScript和PHP。

Cookie 不是唯一的方法,你可以用localStorage,试试这个:

if(localStorage.getItem("firstTime")==null){
   alert("First Time Alert");
   localStorage.setItem("firstTime","done");
}

您应该使用服务器端语言 (php) 来存储会话变量。会话跨页面加载存储数据。

如果您有某种方法来保留用户的状态(如果他们是否访问过该页面),那么您可以将其传递给页面并告诉它显示消息,同时在服务器端(在数据库中或保存该用户/页面数据的任何位置)将页面标记为"已访问"。

如果您没有在任何地方维护该信息,那么您需要使用cookie或localStorage;但是,这些数据可能会丢失(如果用户清除它),然后消息将再次显示。

这是一个非常好的轻量级插件,我有时会使用它。

// plugin start //
    // First Time Visit Processing
    // copyright 10th January 2006, Stephen Chapman
    // permission to use this Javascript on your web page is granted
    // provided that all of the below code in this script (including this
    // comment) is used without any alteration
    function rC(nam) {var tC = document.cookie.split('; '); for (var i = tC.length - 1; i >= 0; i--) {var x = tC[i].split('='); if (nam == x[0]) return unescape(x[1]);} return '~';} function wC(nam,val) {document.cookie = nam + '=' + escape(val);} function lC(nam,pg) {var val = rC(nam); if (val.indexOf('~'+pg+'~') != -1) return false; val += pg + '~'; wC(nam,val); return true;} function firstTime(cN) {return lC('pWrD4jBo',cN);} function thisPage() {var page = location.href.substring(location.href.lastIndexOf(''/')+1); pos = page.indexOf('.');if (pos > -1) {page = page.substr(0,pos);} return page;}
// plugin finish //

// example code to call it - you may modify this as required
function start() {
   if (firstTime(thisPage())) {
      // this code only runs for first visit
      alert('welcome');
   }
   // other code to run every time once page is loaded goes here
}
onload = start;

示例 http://javascript.about.com/library/blfirst1.htm