仅在用户首次访问网站时运行jQuery代码 [英] Run jQuery code only the first time a user visits the website

查看:83
本文介绍了仅在用户首次访问网站时运行jQuery代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码

setTimeout(function () {
    $("#videoOverlay").fadeIn();
    document.getElementById("video").play();
}, 8000);

这意味着加载后8秒钟,将弹出一个弹出窗口,并播放视频.我只希望在我第一次访问该站点时出现这种情况.我该如何使用jQuery?

This means 8 seconds after loading, a pop-up will come up and a video will play. I only want this to come up the first time I visit the site. How can I do this with jQuery?

推荐答案

尝试使用 localStorage 而不是cookie:

Try with localStorage instead of cookie:

if (!localStorage.getItem('viewed')){
    setTimeout(function () {
        $("#videoOverlay").fadeIn();
        document.getElementById("video").play();
        localStorage.setItem('viewed','yes');
    }, 8000);
};

要删除它:

localStorage.removeItem('viewed');

有了本地存储,Web应用程序可以在用户的​​浏览器中本地存储数据.

With local storage, web applications can store data locally within the user's browser.

http://www.w3schools.com/html/html5_webstorage.asp

什么是HTML本地存储?

在HTML5之前,应用程序数据必须存储在cookie中,并包含在每个服务器请求中.本地存储更安全,可以在不影响网站性能的情况下在本地存储大量数据.

Before HTML5, application data had to be stored in cookies, included in every server request. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance.

与cookie不同,存储限制更大(至少5MB),并且信息永远不会传输到服务器.

Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.

本地存储是每个来源的(每个域和协议).所有页面,从一个来源出发,都可以存储和访问相同的数据.

Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

使用: sessionStorage

您还可以使用与 localStorage 对象相同的 sessionStorage 对象,不同之处在于它仅存储一个会话的数据.当用户关闭特定的浏览器选项卡时,数据将被删除.

You can also use sessionStorage object that is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.

if (!sessionStorage.viewed){
    setTimeout(function () {
        $("#videoOverlay").fadeIn();
        document.getElementById("video").play();
        sessionStorage.viewed=1
    }, 8000);
};

这篇关于仅在用户首次访问网站时运行jQuery代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆