Home > Web Front-end > JS Tutorial > body text

Simple application of javascript cookies_javascript skills

WBOY
Release: 2016-05-16 15:13:44
Original
1582 people have browsed it

In my usual process of developing web pages, it may involve local storage of the browser. The current mainstream browser storage methods include: cookies, direct reading of xml, userData, H5 LocalStorage, etc. Cookies store data is limited, but It is more convenient to operate when the amount of data is not large.

The following example is mainly to pop up a prompt box when the web page is opened, but the prompt box will not be displayed when the web page is refreshed after the second time. Of course, the cookie time can be flexibly set to control whether to display the prompt box.

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
</head>
<body>

<script>

  var cookie = {
    setCookie:function(name,value,iDay){
      var cookieStr = '';
      if(iDay == undefined){
        cookieStr += name+'='+value+';';
      }else{
        var oDate = new Date();
        oDate.setDate(oDate.getDate()+iDay);
        cookieStr += name+'='+value+';express='+oDate;
      }

      document.cookie = cookieStr;
    },
    getCookie:function(name){
      var arr = document.cookie.split(';');
      for(var i=0;i<arr.length;i++){
        var arr2 = arr[i].split('=');
        if(arr2[0] == name){
          return arr2[1];
        }
      }
      return '';
    },
    removeCookie:function(name){
      this.setCookie(name,'1',-1);
    }
  }

  function ControlAlert(){
    var flag = cookie.getCookie('flag');
    if(!flag){
      alert("我是第一次加载的哟!");
      cookie.setCookie('flag',true);
      //cookie.setCookie('flag',true,1);//如果有第三个参数则保存cookie的天数,如果不设置,浏览器关闭时cookie过期
    }
  }

  (function(){
    ControlAlert();
  }());

</script>
</body>
</html>
Copy after login

The above are the related operations of cookied. I hope it will be helpful to everyone's learning.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!