jQuery.Cookie を利用して Cookieに書き込まれた値を削除するコードを紹介します。
書式
通常は、"removeCookie()" メソッドを利用します。
$.removeCookie([削除するCookieのキー名]);
コード
下記のコードを記述します。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="jquery-2.1.4.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<title></title>
<meta charset="utf-8" />
<script type="text/javascript">
$(document).ready(function () {
$.removeCookie("Name");
$.removeCookie("Age");
$("#msg").text("Cookieをクリアしました。");
});
</script>
</head>
<body>
<div id="msg"></div>
</body>
</html>
実行結果
Cookieに値が書き込まれている状態にします。書き込まれている値を確認します。Cookieに書き込まれている値を参照するコードは
こちらの記事を参照してください。
上記のHTMLファイルにWebブラウザでアクセスします。下図の画面が表示されます。
先ほどのCookieの値を確認するページをWebブラウザで開きます。値がクリアされ、"undefined" になっていることが確認できます。
別の方法
別の方法として、Cookieの値書き込み時にnullを与えて、nullで上書きする方法があります。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="jquery-2.1.4.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<title></title>
<meta charset="utf-8" />
<script type="text/javascript">
$(document).ready(function () {
$.cookie("Name", null);
$.cookie("Age", null);
$("#msg").text("Cookieをクリアしました。");
});
</script>
</head>
<body>
<div id="msg"></div>
</body>
</html>
また、Expires に -1を与えてCookieを有効期限切れにして、クリアする方法もあります。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="jquery-2.1.4.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<title></title>
<meta charset="utf-8" />
<script type="text/javascript">
$(document).ready(function () {
$.cookie("Name","", {expires: -1});
$.cookie("Age", "", {expires: -1});
$("#msg").text("Cookieをクリアしました。");
});
</script>
</head>
<body>
<div id="msg"></div>
</body>
</html>
著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2024-01-06
作成日: 2015-12-29