Javascript 如何在jquery中设置会话变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11123622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:34:57  来源:igfitidea点击:

How to set session variable in jquery?

javascriptjqueryhtml

提问by capri

I have an html page that open a popup window when the page loads.

我有一个 html 页面,页面加载时会打开一个弹出窗口。

I need to set the popup only when the page open first time. I think session or cookie is to be set.

我只需要在第一次打开页面时设置弹出窗口。我认为要设置会话或 cookie。

    <script>
        !window.jQuery && document.write('<script src="fancybox/jquery-1.4.3.min.js"><\/script>');
    </script>
    <script type="text/javascript" src="fancybox/jquery.fancybox-1.3.4.pack.js"></script>       
    <script type="text/javascript">
    $(document).ready(function() {  
        $("a#example1").fancybox();     
        $("a#example1").trigger('click');           
    });

    </script>   
    <link rel="stylesheet" type="text/css" href="fancybox/jquery.fancybox-1.3.4.css" media="screen" />  
</head>
<body>
<a id="example1" href="images/pic.jpg"></a> 
</body>

回答by Denys Séguret

Use localStorageto store the fact that you opened the page :

使用localStorage存储您打开页面的事实:

$(document).ready(function() {
    var yetVisited = localStorage['visited'];
    if (!yetVisited) {
        // open popup
        localStorage['visited'] = "yes";
    }
});

回答by Cliffton Fernandes

You could try using HTML5s sessionStorage it lasts for the duration on the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.

您可以尝试使用 HTML5s sessionStorage 它持续页面会话的持续时间。只要浏览器打开,页面会话就会持续,并在页面重新加载和恢复后继续存在。在新选项卡或窗口中打开页面将导致启动新会话。

sessionStorage.setItem("username", "John");

sessionStorage.setItem("username", "John");

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage

Browser Compatibility https://code.google.com/p/sessionstorage/compatible with every A-grade browser, included iPhone or Android. http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/

浏览器兼容性https://code.google.com/p/sessionstorage/兼容所有 A 级浏览器,包括 iPhone 或 Android。http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/