jQuery对话框弹出Cookie

Wol*_*Cat 0 javascript cookies jquery

我需要这个弹出窗口,每个访问者只显示一次.当用户单击关闭按钮时,cookie应该触发并将弹出窗口设置为30天不显示.我自己试过安装一个cookie,但无济于事,因为我对JavaScript的理解有限.我在这里看到了几篇与此有关的帖子,但他们对我没有帮助.

JavaScript的:

<link rel="stylesheet" href="jquery-ui-1.10.3.custom/jquery-ui-1.10.3.custom.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$( "#dialog-modal" ).dialog({
height: 380,
width: 500,
modal: true,
buttons: {
    Ok: function() {
        $( this ).dialog( "close" );
        }
    }
});
});
</script>
Run Code Online (Sandbox Code Playgroud)

HTML:

<div id="dialog-modal" title="Please Note:" class="content-list">
    <p>If you are taking advantage of our 21 day risk free trial <strong>your credit card will not be charged for 21 days</strong> after you receive your new biofeedback headband.</p>
    <ul>
        <li>Only Available for residents of the USA</li>
        <li>No Risk - 100% Money-Back Guarantee</li>
        <li>If you’re not satisfied we even pay for your return shipping</li>
    </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

谢谢.

Joh*_*n S 5

您可以使用jquery cookie插件.如果包含该库,则可以执行以下操作:

$(function () {
    if (!$.cookie("notice-accepted")) {
        $("#dialog-modal").dialog({
            height: 380,
            width: 500,
            modal: true,
            buttons: {
                Ok: function () {
                    $.cookie("notice-accepted", 1, { expires : 30 });
                    $(this).dialog("close");
                }
            }
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

注意:您需要添加style="display: none;"到对话框中,<div>以便在不打开对话框时不显示该对话框.

演示JSFiddle

  • @ WolfCat - 一个选项是隐藏X(关闭)按钮.我推荐[此答案]中的技术(http://stackoverflow.com/a/4287933/859640).当然,如果你这样做,你也应该设置`closeOnEscape:false`; 否则,用户仍然可以通过按"Esc"键关闭对话框.([jsfiddle](http://jsfiddle.net/Gvtfx/3/))另一个选择是将设置cookie的代码移动到"close"事件的事件处理程序中.然后无论用户如何关闭对话框,它都将被执行.([的jsfiddle](http://jsfiddle.net/Gvtfx/1/)) (2认同)