Home  >  Article  >  Web Front-end  >  A detailed introduction to JS tool class, how to operate cookies

A detailed introduction to JS tool class, how to operate cookies

php是最好的语言
php是最好的语言Original
2018-07-25 09:24:481192browse

What are the JS tool operations? The following introduces the complete code and implementation principle of operating the Cookie tool class. Rewrite the Cookie tool class, which can be introduced in edit.jsp and used directly in other imported js.

/***
	*读取指定的Cookie值 readCookie("id");
	*@param {string} cookieName Cookie名称
	*/
	function readCookie(cookieName) {
	    var theCookie = "" + document.cookie;
	    var ind = theCookie.indexOf(cookieName);
	    if(ind==-1 || cookieName=="") return "";
	    var ind1 = theCookie.indexOf(';',ind);
	    if(ind1==-1) ind1 = theCookie.length;
	    /*读取Cookie值*/
	    return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
	}
	
	/***
	* 设置Cookie值 setCookie("id",1);
	* @param {string} cookieName Cookie名称
	* @param {string} cookieValue Cookie值
	* @param {number} nDays Cookie过期天数
	*/
	function setCookie(cookieName, cookieValue) {
	    /*当前日期*/
	    var today = new Date();
	    /*Cookie过期时间*/
	    var expire = new Date();
	    /*如果未设置nDays参数或者nDays为0,取默认值1*/
	    //if(nDays == null || nDays == 0) nDays = 1;
	    /*计算Cookie过期时间【 3600000 * 24  为一天】*/
	    expire.setTime(today.getTime() + 400000); //5分钟
	    document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" +      expire.toGMTString();
	}
	
	/***
	* 删除cookie中指定变量函数  
	* @param {string} $name Cookie名称
	*/    
    function deleteCookie($name){    
         var myDate=new Date();    
         myDate.setTime(-1000);//设置时间    
         document.cookie=$name+"=''; expires="+myDate.toGMTString();                
    }
	
	/***
	* 删除cookie中所有定变量函数  
	* @param {string} cookieName Cookie名称
	* @param {string} cookieValue Cookie值
	* @param {number} nDays Cookie过期天数
	*/  
    function clearCookie(){    
         var myDate=new Date();    
         myDate.setTime(-1000);//设置时间    
         var data=document.cookie;    
         var dataArray=data.split("; ");    
         for(var i=0;i<dataArray.length;i++){    
              var varName=dataArray[i].split("=");    
              document.cookie=varName[0]+"=&#39;&#39;; expires="+myDate.toGMTString();    
         }    
    }

Related recommendations:

Introduction to Version Management Tools---SVN Chapter

Video: Introduction to cookie principles, creating cookies and obtaining them cookie


The above is the detailed content of A detailed introduction to JS tool class, how to operate cookies. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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