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

4
我希望能在网页首次加载时展示一个消息框。如果用户刷新页面,消息框不应再次出现。无论用户是否已登录,消息都应该显示。
是使用cookie的唯一方法吗?还是有任何JavaScript库可以处理这个问题?技术栈是jQuery / JavaScript和PHP。

如果您不需要支持旧版浏览器,也可以使用localStorage。 - James Daly
1
有趣...不确定为什么我没想到。谢谢。 - Geocrafter
4个回答

3

不只有Cookies这一种方式,您可以使用localStorage,试试这个:

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

你比我快了——只是一个快速的问题:如果我创建一个对象并尝试访问不存在的属性,它为什么返回 null 而不是 undefined?在这里返回 null,但通常情况下应该返回 undefined。 - James Daly
如果您设置了项目,它将返回未定义。我猜当您设置setItem时。 - James Daly
当进行这样的比较时 ==nullnull 也包括 undefined - Raúl Juárez
啊,是的,这就是为什么应该使用 === ;-) - James Daly

0

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

// 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


0
你应该使用服务端语言(如php)来存储会话变量。会话可以在页面加载之间存储数据。

0

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接