在使用JS Cookie的x页面视图之后显示模态?

我试图显示在我的网站上查看的Bootstrap模态avec 3页面,并使用JS-Cookie插件找到该问题的实际解决方案。


我尝试了这段代码,但没有用:


$(document).ready(function () {

    // create cookie

    var visited = Cookies('visited'); // visited = 0

    if (visited >= 3) {

        // open fancybox after 3 secs on 4th visit or further on the same day

        $('#my_modal').modal('show');

    } else {

        visited++; // increase counter of visits

        // set new cookie value to match visits

        Cookies('visited', visited, {

            expires: 1 // expires after one day

        });

        return false;

    }

}); // ready

上面的代码应该做什么:重新加载4页后提示模态,

什么不起作用:我重新加载页面但模态未出现


这是我的Cookie状态(在Chrome上): 

http://img3.mukewang.com/6078050100014ef809670492.jpg

这是一个代码示例,实际上可用于在网站的首次访问时显示模式:


$(document).ready(function() {

  if (Cookies('pop_welcome') == null) {

         $('#my_modal').modal('show');

     Cookies('pop_welcome', '31', { expires: 31 });

  }

 });

** - 解决方案 - **


您可以在@greedchikara代码段中找到解决方案


编码 :


function createCookie(name,value,days) {

    if (days) {

        var date = new Date();

        date.setTime(date.getTime()+(days*24*60*60*1000));

        var expires = "; expires="+date.toGMTString();

    }

    else var expires = "";

    document.cookie = name+"="+value+expires+"; path=/";

}


function readCookie(name) {

    var nameEQ = name + "=";

    var ca = document.cookie.split(';');

    for(var i=0;i < ca.length;i++) {

        var c = ca[i];

        while (c.charAt(0)==' ') c = c.substring(1,c.length);

        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);

    }

    return null;

}


function eraseCookie(name) {

    createCookie(name,"",-1);

}


var visited = readCookie('tester') || 1;


if (visited > 2) {

  $('#my_modal').modal('show');

} else {

  visited++;

  createCookie('tester', visited, 1);

}

你能帮我么 ?谢谢


四季花海
浏览 135回答 2
2回答

守着一只汪

您可以使用这三个简单的函数来执行cookie任务,而无需第三方库。function createCookie(name,value,days) {&nbsp; &nbsp; if (days) {&nbsp; &nbsp; &nbsp; &nbsp; var date = new Date();&nbsp; &nbsp; &nbsp; &nbsp; date.setTime(date.getTime()+(days*24*60*60*1000));&nbsp; &nbsp; &nbsp; &nbsp; var expires = "; expires="+date.toGMTString();&nbsp; &nbsp; }&nbsp; &nbsp; else var expires = "";&nbsp; &nbsp; document.cookie = name+"="+value+expires+"; path=/";}function readCookie(name) {&nbsp; &nbsp; var nameEQ = name + "=";&nbsp; &nbsp; var ca = document.cookie.split(';');&nbsp; &nbsp; for(var i=0;i < ca.length;i++) {&nbsp; &nbsp; &nbsp; &nbsp; var c = ca[i];&nbsp; &nbsp; &nbsp; &nbsp; while (c.charAt(0)==' ') c = c.substring(1,c.length);&nbsp; &nbsp; &nbsp; &nbsp; if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);&nbsp; &nbsp; }&nbsp; &nbsp; return null;}function eraseCookie(name) {&nbsp; &nbsp; createCookie(name,"",-1);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript