设置一个 jQuery cookie 只显示一次弹出窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8405634/
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-27 10:29:51  来源:igfitidea点击:

Set a jQuery cookie to show popup only once

jquerycookiesif-statementpopup

提问by Peter Amsterdam

I'm an absolute newbie in jQuery. I'm learning, but there is a Christmas message that I need to get up and running within no time.

我是 jQuery 的绝对新手。我正在学习,但有一条圣诞节消息,我需要立即启动并运行。

I've included these in the header of the page:

我已将这些包含在页面的标题中:

<script type="text/javascript" src="scripts/jquery-1.7.min.js"></script>
<script type="text/javascript" src="scripts/jquery.cookies.2.2.0.min.js"></script>` 

Then follows the message using a jQuery popup. Here it is:

然后使用 jQuery 弹出窗口跟踪消息。这里是:

<script type="text/javascript">
$(document).ready(function() {  
        var id = '#dialog';

        //Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        //Set height and width to mask to fill up the whole screen
        $('#mask').css({'width':maskWidth,'height':maskHeight});

        //transition effect     
        $('#mask').fadeIn(1000);    
        $('#mask').fadeTo("slow",0.7);  

        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        //Set the popup window to center
        $(id).css('top',  winH/2-$(id).height()/2);
        $(id).css('left', winW/2-$(id).width()/2-220);

        //transition effect
        $(id).fadeIn(2000);     

    //if close button is clicked
    $('.window .close').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();

        $('#mask').hide();
        $('.window').hide();
    });     

    //if mask is clicked
    $('#mask').click(function () {
        $(this).hide();
        $('.window').hide();
    });     

});

</script>

In the bodyI've put the message:

body我已经把消息:

<div style="top: 199.5px; left: 200px; display: none;" id="dialog" class="window">  
XMAS MESSAGE
<a href="#" class="close">Shut this popup.</a>
</div>

So far so good. The next step would be not to bore my returning visitors with the same message over and over (postpone for sixty days would be good enough).

到现在为止还挺好。下一步是不要一遍又一遍地用相同的信息让我的回访者感到厌烦(推迟六十天就足够了)。

So I want to set a cookie using the jQuery cookie plug-in:

所以我想使用jQuery cookie插件设置一个cookie:

function setCookie() {
    $.cookie('test_status', '1', { path: '/', expires: 60 });
    return false;
}

Which is then found the next time a visitor hits the same page and the Christmas message is not shown till the message expires.

然后在下次访问者点击同一页面时找到它,并且直到消息过期才会显示圣诞节消息。

Now if-elsestatements are the higher kind of jQuery I'm not familiar with just yet. So, could anyone explain it to me?

现在if-else语句是我还不熟悉的高级 jQuery。所以,谁能给我解释一下?

回答by Sudhir Bastakoti

Something of this kind might be of help:

这种东西可能会有所帮助:

$(document).ready(function(){
   if ($.cookie('test_status') != '1') {
    //show popup here
    $.cookie('test_status', '1', { expires: 60}); }
   });

回答by Amit Naraniwal

First include the jquery library.

首先包含 jquery 库。

After include the below script for cookies in jquery.

在 jquery 中包含以下 cookie 脚本之后。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>

Now put the below code into the footer :

现在将以下代码放入页脚:

$(document).ready(function() {
       // initially popup is hidden:
        $('#stay-in-toch.popup-outer').hide();
        // Check for the "whenToShowDialog" cookie, if not found then show the dialog and save the cookie.
        // The cookie will expire and every 2 days and the dialog will show again.
        if ($.cookie('whenToShowDialog') == null) {
            // Create expiring cookie, 2 days from now:
            $.cookie('whenToShowDialog', 'yes', { expires: 2, path: '/' });

            // Show dialog
             $('#stay-in-toch.popup-outer').show();       
        }
    });

回答by ShankarSangoli

You can try this

你可以试试这个

$(document).ready(function() {  
    if ($.cookie('test_status')) {
        return;
    }

    //Rest of your code here
});

回答by Mma87

I had the same problem and I found this solution:

我遇到了同样的问题,我找到了这个解决方案:

$(document).ready(function () {
    var cookie = document.cookie;
    if (cookie == "") {
        //show popup depending on url
        var url = window.location;
        if (url != "http://localhost/test/jquery-popup.html") {                                    
            setTimeout(function () {
                $.fn.colorbox({ html: '<div style="width:301px;height:194px;"><a href="http://livebook.in/"><img src="res/homer.jpg" style="width:301px;height:194px;" alt="The linked image" /></a></div>', open: true });
            }, 500);   
        }else {
            setTimeout(function () {
                $.fn.colorbox({html:'...', open:true});
            }, 500);
        }

        //set timeout for closing the popup
        setTimeout(function () { $.fn.colorbox.close(); }, 3000);

        //set cookie
        var d = new Date();
        d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000)); //expire in 30 days
        var expires = "expires=" + d.toGMTString();
        document.cookie = "apparsoYES" + "=" + "YES" + "; " + expires;    
    }
});

this script creates a popup on page load, auto close it, creates a cookie so the popoup is showed only once time and can show different popups depending on the page

此脚本在页面加载时创建一个弹出窗口,自动关闭它,创建一个 cookie,因此该弹出窗口仅显示一次,并且可以根据页面显示不同的弹出窗口

回答by iamabhishek

I guess what you are looking for is, when a new user visits your Webpage, you show a pop up, but as he surfs through other pages, the pop window should not come up.

我猜您要寻找的是,当新用户访问您的 时Webpage,您会显示一个弹出窗口,但是当他浏览其他页面时,弹出窗口不应该出现。

Its very easy to achieve through cookies, check this code sample, this will help you

通过它很容易实现cookies,请查看此代码示例,这将对您有所帮助

So i am including the code snippet used(you can also follow the below link for the same)

所以我包含了使用的代码片段(您也可以按照以下链接进行操作)

So, the script part is

所以,脚本部分是

var expDays = 1; // number of days the cookie should last

var page = "only-popup-once.html";
var windowprops = "width=300,height=200,location=no,toolbar=no,menubar=no,scrollbars=no,resizable=yes";

function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}
function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function amt(){
var count = GetCookie('count')
if(count == null) {
SetCookie('count','1')
return 1
}
else {
var newcount = parseInt(count) + 1;
DeleteCookie('count')
SetCookie('count',newcount,exp)
return count
   }
}
function getCookieVal(offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}

function checkCount() {
var count = GetCookie('count');
if (count == null) {
count=1;
SetCookie('count', count, exp);

window.open(page, "", windowprops);

}
else {
count++;
SetCookie('count', count, exp);
   }
}

And following will be the body of DOM,

以下将是 DOM 的主体,

<BODY OnLoad="checkCount()">

http://www.jsmadeeasy.com/javascripts/Cookies/Only%20Popup%20Once/index.htm

http://www.jsmadeeasy.com/javascripts/Cookies/Only%20Popup%20Once/index.htm

回答by pinkp

Using js-cookie https://github.com/js-cookie/js-cookie

使用 js-cookie https://github.com/js-cookie/js-cookie

And Magnific Popup http://dimsemenov.com/plugins/magnific-popup/

和 Magnific Popup http://dimsemenov.com/plugins/magnific-popup/

And inspired by the other answers I did this which I'm posting as it took me ages to work out so may help someone else. If anyone wants to edit and improve my code feel free.

并受到其他答案的启发,我做了这个,因为我花了很长时间才能解决这个问题,所以可能会帮助其他人。如果有人想编辑和改进我的代码,请随意。

 <script type="text/javascript">
function setCookie() {
    Cookies.set('test_status', '1', { expires: 1 })
    return false;
}
</script>

<script type="text/javascript">//<![CDATA[
$(document).ready(function(){
   if (Cookies.get('test_status') != '1') {
         setTimeout(function(){
    $.magnificPopup.open({
     items: {
            src: '#message_popup' //ID OF INLINE ELEMENT
                },
            type:'inline',
      mainClass: 'mfp-zoom-out',
       closeBtnInside: true,
        fixedContentPos: true,
        removalDelay: 500,
            });
     }, 3000);  // equals 50 seconds
    Cookies.set('test_status', '1', { expires: 1}); }
   });
  //]]>
</script>

<script type="text/javascript">
  function closePopup() {
  $.magnificPopup.close();
}
</script>

//MY POP UP
<div id="message_popup" class="white-popup mfp-hide typography">
<button title="CLOSE" type="button" onClick="closePopup();">x</button>
  <div id="pop_inner">
   HELLO WORLD
  </div>
</div>