繁体   English   中英

如何在第一次加载页面时使用JavaScript / jQuery显示消息框?

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

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

Cookie是唯一可以做到这一点的方法,还是有任何JavaScript库可以解决这个问题? 技术堆栈是jQuery / JavaScript和PHP。

Cookies不是唯一的方法,你可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM