1

我正在努力在 html 页面上使用 Cookie。我想要一个脚本检查用户是否有 cookie,如果没有则调用此脚本来打开模型窗口

<script type="text/javascript">
jQuery(document).ready(function() {
  jQuery("#myModal").reveal();
});
</script

该窗口包含“是”和“否”按钮,如果您的用户选择“是”,它将保存一个 cookie,因此在以后访问该页面时模式不会打开,如果用户选择“否”,它将简单地引导它们到另一个页面。

4

1 回答 1

1

1) 使用 jQuery cookie 库以方便使用。https://github.com/carhartl/jquery-cookie
2) 检查cookie是否存在并进行相应处理

if ($j.cookie("NameOfYourCookie") == null) {
//Do stuff if cookie doesn't exist like set a cookie with a value of 1
$j.cookie("NameOfYourCookie", 1, {expires: 10, path:'/'});
}

else {
//They have a cookie so do something
alert ('You have a cookie with name NameOfYourCookie');
}

* 编辑 *

以为我可能会编辑我的答案以更适合您的问题。

        <button class="yes">YES</button>
        <button class="no">No</button>

     var $j = jQuery.noConflict();

$j(document).ready(function(){
//Show modal on page load           
$j("#myModal").show();  



$j('.yes').click(function(){
        $j("#myModal").hide();
        $j.cookie("YesButtonCookie", 1, {expires: 10, path:'/'});
        alert ('You have clicked yes, a cookie has been dropped');

  });


        if ($j.cookie("YesButtonCookie") == 1){
            // Don't show the div
            $j("#myModal").hide(); 
            alert ('Cookie found, you cant see myModal');
        }


        if ($j.cookie("YesButtonCookie") == null){
                    // Cookie Not Found
                    alert ('Cookie Not found, you can see myModal');
                    $j("#myModal").show();
        }




    $j('.clearcookie').click(function(){
        $j.cookie("YesButtonCookie", null);
        alert('Cookie Cleared');
    });


});

JSFIDDLE 测试

于 2013-04-05T00:39:47.563 回答