Home > Web Front-end > JS Tutorial > Example code sharing of cookie implementation of message board

Example code sharing of cookie implementation of message board

零下一度
Release: 2017-07-18 13:27:04
Original
1693 people have browsed it

Cookie implementation of message board example code sharing

Direct code:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style>
	#input{
		width: 400px;
		height: 400px;
	}
</style>
<script>
	function setCookie(name, value, iDay){
	  var oDate=new Date();
	  
	  //用来设置过期时间用的,获取当前时间加上传进来的iDay就是过期时间
	  oDate.setDate(oDate.getDate()+iDay); 
	  document.cookie=name+&#39;=&#39;+value+&#39;;expires=&#39;+oDate;
	  
	};
	function getCookie(name){
		//多个cookie值是以; 分隔的,用split把cookie分割开并赋值给数组
	  var arr=document.cookie.split(&#39;; &#39;); 
	  
	  for(var i=0;i<arr[i].length;i++){
	  	//原来割好的数组是:user=simon,再用split(&#39;=&#39;)分割成:user simon 这样可以通过arr2[0] arr2[1]来分别获取user和simon 
	    var arr2=arr[i].split(&#39;=&#39;); 
	    
	     //如果数组的属性名等于传进来的name
	    if(arr2[0]==name){
	    	 //就返回属性名对应的值
	      return arr2[1];
	    }
	    return &#39;&#39;; //没找到就返回空
	  }
	};
	function removeCookie(name){
		  //-1就是告诉系统已经过期,系统就会立刻去删除cookie
	  setCookie(name, 1, -1); 
	};
	window.onload=function(){
	  var form=document.getElementById(&#39;form&#39;);
	  var user=document.getElementsByName(&#39;user&#39;)[0];
	  form.onsubmit=function(){
	    setCookie(&#39;user&#39;, user.value, 14);
	  };
	  user.value=getCookie(&#39;user&#39;);
	};
</script>
</head>
<body>
<form action="" id="form">
<textarea type="text" name="user" id="input"></textarea><br />
  <input type="submit" value="发表" />
</form>
</body>
</html>
Copy after login

That’s it! The effect is there but I don’t quite understand it! It feels like, Every programmer is an angel whose mouth has been silenced by God!! φ(>ω<*)

The above is the detailed content of Example code sharing of cookie implementation of message board. For more information, please follow other related articles on the PHP Chinese website!

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