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

19

我是一个完全不懂jQuery的新手。我正在学习,但有一条圣诞信息需要在很短时间内上线。

我已经将以下内容包含在页面的头部:

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

接下来使用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>

我在 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>

目前为止都很好。下一步是不要让我的回访者反复看到相同的消息而感到无聊(推迟六十天应该足够好了)。

因此,我想使用jQuery cookie插件设置一个cookie:

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

下次访问同一网页时,将找到这个 cookie,并且在消息过期之前不会再显示圣诞节的消息。

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


当关闭事件触发时,运行cookie函数。然后在代码顶部检查cookie值。如果存在,则不显示模态框。 - Seth
jQuery不是一种语言,它没有if-else语句。它只是一堆JavaScript代码。在JavaScript中,if-else语句就像任何编程语言中的条件语句一样。 - Esailija
6个回答

16

这样的代码可能会有所帮助:

$(document).ready(function(){
   if ($.cookie('test_status') != '1') {
    //在此处显示弹出窗口
    $.cookie('test_status', '1', { expires: 60}); }
   });

谢谢,我已经苦苦挣扎了很久,试图让 cookie 正常工作。 - lharby
1
jquery.cookie在新的代码库中更名为js-cookie:https://github.com/js-cookie/js-cookie。在2.0.0版本中,已删除了`$`(jquery依赖)。 - Fagner Brack

3
首先,包含 jQuery 库。
然后,包括以下脚本以使用 jQuery 处理 cookies。
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>

现在将以下代码放入页脚中:
$(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();       
        }
    });

很棒的插件,易于使用。文档可以在这里找到:https://github.com/carhartl/jquery-cookie#readme - HPWD

2
你可以尝试这个。
$(document).ready(function() {  
    if ($.cookie('test_status')) {
        return;
    }

    //Rest of your code here
});

0
我猜你想要的是,当一个新用户访问你的网页时,你会显示一个弹出窗口,但是当他浏览其他页面时,弹出窗口不应该再次出现。
这可以通过使用cookies来轻松实现,检查以下代码示例,这将有助于您:
因此,我包含了使用的代码片段(您也可以跟随下面的链接进行操作)。
所以,脚本部分是:
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);
   }
}

接下来将是DOM的主体部分。

<BODY OnLoad="checkCount()">

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


0

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

$(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;    
    }
});

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

请注意,document.cookie将返回所有的cookie而不仅仅是你的apparsoYES cookie。 - Daniel J.G.

0

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

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

受其他答案的启发,我做了这个,我把它发布出来,因为我花了很长时间才弄清楚,可能会帮助其他人。如果有人想编辑和改进我的代码,请随意。

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

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