ホームページ  >  記事  >  ウェブフロントエンド  >  jqueryでのCookieの使用例(取得、保存、削除など)を詳しく解説_jquery

jqueryでのCookieの使用例(取得、保存、削除など)を詳しく解説_jquery

WBOY
WBOYオリジナル
2016-05-16 15:21:591520ブラウズ

この記事の例では、jquery での Cookie の使用法について説明します。参考のために皆さんと共有してください。詳細は次のとおりです:

jqueryではCookieには指定されたCookie操作クラスがあります。 まずCookie操作クラスを使用する際の問題点を紹介し、その後に正しい使用方法を紹介します。

JQuery を使用して Cookie を操作すると、不正な値が発生します:
Cookie には 4 つの異なる属性があることがわかりました:
名前、コンテンツ、ドメイン、パス

$.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 が生成されます

コードをコピー コードは次のとおりです:
$.cookie("currentMenuID");

値を取得するときに問題が発生します。

それで:

コードをコピー コードは次のとおりです:
$.cookie("currentMenuID", "menuID", { path: "/" });

カバーするために。同じドメイン内の同じ cookieID が値に対応します。

例を見てみましょう

Cookie のパス設定に関する注意事項: path:'/' が設定されていない場合、パスはディレクトリに従って自動的に設定されます (例: 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 操作 Cookie は、ユーザーがクエリした情報を記録します

これは Cookie データによって生成されたリストです、

クリックしてクエリを実行するたびに、ドメイン名が保存され、最後にクエリされたドメイン名が先頭に表示されます。この例では最大 10 個の項目を保存できます。状況に応じて設定できます

それを達成する方法を見てみましょう

まずCookieを操作するための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;
}

これを完了したら、クエリをクリックしたときに Cookie を保存するだけです。以下の方法を参照してください。

Cookie クラスの操作

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);

OK、機能は完了しました。

特定のテストを実施する

コードはあまり適切に書かれていません。対応する修正を加えて改善に努めるため、さらに提案をいただければ幸いです。

Cookie はクライアント側に保存されます。1 つの Cookie は同じドメイン名でのみアクセスできます。保存方法は次のとおりです。

コードをコピー コードは次のとおりです:
$.cookie("domain", value, {有効期限: 7,ドメイン: " 7c.com" });

時刻を取得するには $.cookie("domain"); と記述するだけで、サブドメイン名であればこのように呼び出すことができ、このドメイン名で Cookie 共有機能を実現できます。

Cookie を効果的に使用すると、当社の Web サイトに多くの予期せぬ効果や機能がもたらされます。ぜひ共有してください

jQuery の Cookie 操作の詳細については、このサイトの特別トピック「 jQuery の Cookie 操作スキルの概要 」を参照してください。

この記事が jQuery プログラミングのすべての人に役立つことを願っています。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。