使用cookie仅在第一页加载时加载彩盒

时间:2011-05-22 09:06:25

标签: javascript jquery colorbox

我尝试过网络上的参考代码,只在页面加载时加载一个特定元素

以下是示例代码


    <script type="text/javascript">
        $(document).ready(function(){
    $.colorbox({width:"40%", height:"63%", inline:true, href:"#subscribe"});
}); 
</script>
 <script type="text/javascript"> 
  $(document).ready(function(){
             if (document.cookie.indexOf('visited=true') === -1) {
                   var expires = new Date();
                   expires.setDate(expires.getDate() 31);
                   document.cookie = "visited=true;
expires=" expires.toUTCString();
               } 
             </script> 

有人可以指导我,这个代码有什么问题

这是我正在编辑的html页面


<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset=utf-8 />
    <title>Popup Subscription Box</title>
    <style type="text/css">
        body{font:12px/1.2 Verdana, Arial, san-serrif; padding:0 10px;}
        a:link, a:visited{text-decoration:none; color:#416CE5; border-bottom:1px solid #416CE5;}
        h2{font-size:13px; margin:15px 0 0 0;}
    </style>
    <link media="screen" rel="stylesheet" href="colorbox.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script&gt;
    <script src="../colorbox/jquery.colorbox-min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
    $.colorbox({width:"30%", inline:true, href:"#subscribe"});
}); 
</script>
 <script type="text/javascript"> 
  jQuery(document).ready(function(){
             if (document.cookie.indexOf('visited=true') == -1) {
                   var expires = new Date();
                   expires.setDate(expires.getDate() 31);
                   document.cookie = "visited=true;
expires=" expires.toUTCString();
               } 
             </script> 
<style type="text/css">
.example8 { display:none; }
</style>
</head>
<body>
    <h1>Demonstration</h1>

*/ Here is the div id=subscribe info goes */

</body> </html>

1 个答案:

答案 0 :(得分:7)

你的cookie集是......有点可怕的破坏(例如,这个:“expires.setDate(expires.getDate()31);”并不意味着什么。你没有一个运算符(加上在getDate和31之间。你似乎也有一个换行符,这会破坏一切。

可能更重要的是,你需要在程序流程中实际调用colorbox,否则,你每次都会调用它。

如果您转储其他脚本(立即启动colorbox的脚本),并且如果您在页面上实际拥有ID为subscribe的div,则以下内容适用于您:

jQuery(document).ready(function(){
    if (document.cookie.indexOf('visited=true') == -1) {
        var fifteenDays = 1000*60*60*24*15;
        var expires = new Date((new Date()).valueOf() + fifteenDays);
        document.cookie = "visited=true;expires=" + expires.toUTCString();
        $.colorbox({width:"30%", inline:true, href:"#subscribe"});
    }
});

这是Fiddle

相关问题