>  기사  >  웹 프론트엔드  >  jquery에서의 쿠키 사용 예(획득, 저장, 삭제 등)에 대한 자세한 설명_jquery

jquery에서의 쿠키 사용 예(획득, 저장, 삭제 등)에 대한 자세한 설명_jquery

WBOY
WBOY원래의
2016-05-16 15:21:591518검색

이 문서의 예에서는 jquery의 쿠키 사용을 설명합니다. 참고하실 수 있도록 모든 사람과 공유하세요. 자세한 내용은 다음과 같습니다.

쿠키에는 jquery에 지정된 쿠키 작업 클래스가 있습니다. 먼저 쿠키 작업 클래스를 사용할 때 발생하는 몇 가지 문제를 소개하고 올바른 사용 방법을 소개하겠습니다.

JQuery를 사용하여 쿠키를 작동할 때 잘못된 값이 발생합니다:
쿠키에는 네 가지 속성이 있는 것으로 나타났습니다.
이름, 콘텐츠, 도메인, 경로

$.cookie('the_cookie'); // 读取 cookie 
$.cookie('the_cookie', 'the_value'); // 存储 cookie 
$.cookie('the_cookie', 'the_value', { expires: 7 }); // 存储一个带7天期限的 cookie 
$.cookie('the_cookie', '', { expires: -1 }); // 删除 cookie

사용:

코드 복사 코드는 다음과 같습니다.
$.cookie("currentMenuID", menuID);

도메인과 경로가 지정되지 않은 경우.

도메인과 경로가 다를 경우 모든 쿠키가 생성됩니다

코드 복사 코드는 다음과 같습니다.
$.cookie("currentMenuID");

가치를 취할 때 문제가 발생합니다.

그래서:

코드 복사 코드는 다음과 같습니다.
$.cookie("currentMenuID", "menuID", { 경로: "/" });

덮다. 동일한 도메인의 동일한 cookieID는 값에 해당합니다.

예제를 살펴보겠습니다

쿠키 ​​경로 설정에 대한 참고사항: '/' 경로를 설정하지 않으면 경로는 [예: http://www.xxx.com/user/, 경로는 ' /user']

로 설정됩니다.
$.extend({ 
/** 
 1. 设置cookie的值,把name变量的值设为value  
example $.cookie('name', ‘value'); 
 2.新建一个cookie 包括有效期 路径 域名等 
example $.cookie('name', ‘value', {expires: 7, path: ‘/', domain: ‘jquery.com', secure: true}); 
3.新建cookie 
example $.cookie('name', ‘value'); 
4.删除一个cookie 
example $.cookie('name', null); 
5.取一个cookie(name)值给myvar 
var account= $.cookie('name'); 
**/
  cookieHelper: function(name, value, options) { 
    if (typeof value != 'undefined') { // name and value given, set cookie 
      options = options || {}; 
      if (value === null) { 
        value = ''; 
        options.expires = -1; 
      } 
      var expires = ''; 
      if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { 
        var date; 
        if (typeof options.expires == 'number') { 
          date = new Date(); 
          date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); 
        } else { 
          date = options.expires; 
        } 
        expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE 
      } 
      var path = options.path ? '; path=' + options.path : ''; 
      var domain = options.domain ? '; domain=' + options.domain : ''; 
      var secure = options.secure ? '; secure' : ''; 
      document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); 
    } else { // only name given, get cookie 
      var cookieValue = null; 
      if (document.cookie && document.cookie != '') { 
        var cookies = document.cookie.split(';'); 
        for (var i = 0; i < cookies.length; i++) { 
          var cookie = jQuery.trim(cookies[i]); 
          // Does this cookie string begin with the name we want&#63; 
          if (cookie.substring(0, name.length + 1) == (name + '=')) { 
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
            break; 
          } 
        } 
      } 
      return cookieValue; 
    } 
  } 
});

Jquery 작업 쿠키는 사용자가 쿼리한 정보를 기록합니다.

쿠키 데이터로 생성된 목록입니다.

클릭하여 쿼리할 때마다 도메인 이름이 저장되며, 마지막으로 쿼리된 도메인 이름이 맨 위에 표시됩니다. 본 예시는 최대 10개 항목까지 저장할 수 있으며, 상황에 맞게 설정이 가능합니다

이를 달성하는 방법을 살펴보겠습니다

먼저 쿠키를 동작시키기 위한 JS 파일을 다음과 같이 작성하세요

function getid(id) {
return (typeof id == 'string') &#63; document.getElementById(id) : id
};
function getOffsetTop(el, p) {
var _t = el.offsetTop;
while (el = el.offsetParent) {
if (el == p) break;
_t += el.offsetTop
}
return _t
};
function getOffsetLeft(el, p) {
var _l = el.offsetLeft;
while (el = el.offsetParent) {
if (el == p) break;
_l += el.offsetLeft
}
return _l
};
var currentInput = null;
function BoxShow(e) {
var input = e;
if (!input.id) {
input = e.target &#63; e.target : e.srcElement;
}
currentInput = input;
FillUrls("site");
var box = getid("allSitesBoxHdl");
if (box.style.display == 'block' && currentInput.id == input.id) {
return;
}
box.style.left = (getOffsetLeft(input)) + 'px';
box.style.top = (getOffsetTop(input) + (input.offsetHeight - 1)) + 'px';
box.style.width = (input.offsetWidth - 4) + 'px';
box.style.display = 'block';
}
function BoxShowUrls(e) {
BoxShow(e);
}
function InputSetValue(val) {
var obj = currentInput;
obj.value = val;
if (obj.getAttribute('url') == 'true') {
var tags = document.getElementsByTagName('input');
for (var i = 0; i < tags.length; i++) {
if (tags[i].getAttribute('url') == 'true' && tags[i] != obj) {
tags[i].value = val;
}
}
}
BoxHide();
}
//删除时使用,传入一个要删除的值就可以删除
function DelAllSitesValue(value) {
var allSites = $.cookie("site");
allSites = allSites.replace(value + "|", "");
$.cookie("site", allSites, { expires: 7 });
FillUrls("site");
}
function BoxHide() {
if (getid("allSitesBoxHdl")) {
getid("allSitesBoxHdl").style.display = 'none';
}
}
//加载列表
function FillUrls(cookieName) {
var urls = $.cookie(cookieName);
var html = "";
if (urls) {
var urllist = urls.split('|');
var forlength = 0;
var stringcookie;
for (var i = urllist.length - 1; i >= 0; i--) {
var textval = urllist[i];
if ($.trim(textval) != "" && $.trim(textval) != "undefined") {
html += "<li class="lis"><a href="javascript:InputSetValue('" + textval + "');">" + textval + "</a></li><br/>";
forlength = forlength + 1;
if (forlength > 10) {
$.cookie("site", stringcookie, { expires: 7 });
break;
} else {
stringcookie = textval + "|" + stringcookie;
}
}
}
} else {
html += "<li>没有记录</li>"
}
getid("allSitesBoxContent").innerHTML = html;
}
function closeIME(e) {
var obj = e.target &#63; e.target : e.srcElement;
obj.style.imeMode = 'disabled';
}
function OnPaste(e) {
var obj = e.target &#63; e.target : e.srcElement;
setTimeout("MoveHttp('" + obj.id + "')", 100);
}
function MoveHttp(id) {
var val = getid(id).value;
val = val.replace("http://", "");
if (val[val.length - 1] == '/') {
val = val.substring(0, val.length - 1);
}
getid(id).value = val;
}
function OnKeyup(e) {
var obj = e.target &#63; e.target : e.srcElement;
setTimeout("addInput('" + obj.id + "')", 200);
}
function addInput(id) {
var obj = getid(id);
//如果是一个没有True的input不执行
if (obj.getAttribute('url') == 'true') {
if (obj.value.indexOf('。') > 0) {
obj.value = obj.value.replace('。', '.');
}
var tags = document.getElementsByTagName('input');
for (var i = 0; i < tags.length; i++) {
if (tags[i].getAttribute('url') == 'true' && tags[i] != obj) {
tags[i].value = obj.value;
}
}
}
}
function Init() {
$("#allSitesBoxHdl")[0].style.display = 'none';
$(":text").each(function () {
$(this).bind("keyup", OnKeyup);
$(this).bind("mousedown", BoxShowUrls);
$(this).bind("mouseout", BoxHide);
$(this).bind("focus", closeIME);
$(this).bind("paste", OnPaste);
$(this).bind("mouseout", BoxHide);
$(this)[0].setAttribute('autocomplete', 'off');
});
//取出Cookie
var icpSite = $.cookie("site");
if (icpSite) {
//取出Cookie不为空的话就给当前框
icpSite = icpSite.split('|')[0];
$("#site").val(icpSite);
}
}

이것은 아래와 같이 여러 입력창의 값을 동시에 입력하는 효과도 함께 옵니다

해당 입력 상자에 이 효과를 사용하려면 속성을 url="true"로 추가하면 됩니다. 이는 편리하고 작동 가능합니다. 해당 상자에 효과를 추가하려면 이 속성을 추가하면 됩니다. 추가하고 싶지 않다면 추가하지 마세요. url="true"
괜찮습니다.

이 효과를 사용하는 인터페이스에 다음 코드를 추가하세요

<div style="display: none; position: absolute;" id="allSitesBoxHdl" class="classlist"
  onmouseover="this.style.display='block'" onmouseout="this.style.display='none'">
  <ul id="allSitesBoxContent">
  </ul>
</div>
<script type="text/javascript">
Init();
</script>

다른 JS를 Js 파일에 직접 배치하고
에 인용하면 됩니다. 드롭다운 목록은 어떻게 로드되나요? 아래 방법 중 하나를 통해 알아보세요

로드 목록

function FillUrls(cookieName) {
var urls = $.cookie(cookieName);
var html = "";
if (urls) {
var urllist = urls.split('|');
var forlength = 0;
var stringcookie;
for (var i = urllist.length - 1; i >= 0; i--) {
var textval = urllist[i];
if ($.trim(textval) != "" && $.trim(textval) != "undefined") {
html += "<li class="lis"><a href="javascript:InputSetValue('" + textval + "');">" + textval + "</a></li><br/>";
forlength = forlength + 1;
if (forlength > 10) {//在这里我只加载10条,大家可以根据自己的情况进行调整
$.cookie("site", stringcookie, { expires: 7 });
break;
} else {//如果超出10个的话就取最后10个
stringcookie = textval + "|" + stringcookie;
}
}
}
} else {
html += "<li>没有记录</li>"
}
getid("allSitesBoxContent").innerHTML = html;
}

이 작업을 완료한 후 쿼리를 클릭할 때만 쿠키를 저장하면 됩니다.

쿠키클래스 운영

function setCookie(name, value) {
var oldcookie = $.cookie(name);
if (oldcookie == null) {
$.cookie(name, value, { expires: 7 });
} else {
if ($.cookie(name).indexOf(value) == -1) {
$.cookie(name, oldcookie + "|" + value, { expires: 7 });
} else {
$.cookie(name, oldcookie.replace(value, "") + "|" + value, { expires: 7 });
}
}
FillUrls(name);
}

전화할 때 이렇게 적어주세요

코드 복사 코드는 다음과 같습니다.
setCookie("site", strdomin);

좋아, 기능이 완료되었습니다.

특정 테스트 실시

코드가 잘 작성되지 않았습니다. 개선할 수 있도록 더 많은 제안을 해주시기 바랍니다.

쿠키는 클라이언트 측에 저장됩니다. 하나의 쿠키는 동일한 도메인 이름의 쿠키에만 접근할 수 있습니다. 도메인 속성을 추가하면 됩니다.

코드 복사 코드는 다음과 같습니다.
$.cookie("domain", value, { 만료: 7, 도메인: " 7c.com" });

시간을 얻으려면 $.cookie("domain"); 을 작성하면 됩니다. 하위 도메인 이름인 한 이렇게 호출하면 이 도메인 이름으로 쿠키 공유 기능을 구현할 수 있습니다.

쿠키의 효과적인 사용은 당사 웹사이트에 예상치 못한 많은 효과와 기능을 가져올 것입니다. 공유해 주세요

jQuery의 쿠키 작업에 대한 자세한 내용은 이 사이트의 특별 주제인 "JQuery의 쿠키 작업 기술 요약"을 참조하세요.

이 기사가 jQuery 프로그래밍에 종사하는 모든 사람에게 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.