我正在为特定域设置myCookie,当设置cookie时我想隐藏内容,但show / hide IF语句根本不起作用。
我想使用jquery .cookie插件,但这是我到目前为止所拥有的。写cookie确实有效,我只是无法使隐藏功能正常运行。
var cookieName = 'myCookie';
var cookieValue = 'myCookie';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate
+ ";domain=.example.com;path=/";
$(document).ready(function(){
if ($.cookieName('myCookie') >= 0) {
$('.myContent').hide();
}
});
HTML
<div class="myContent">
hide this content if the cookie is set
</div>
otherwise show this content if you don't have the required cookie
非常感谢任何帮助!
答案 0 :(得分:1)
首先,在您的信息页中下载 https://github.com/carhartl/jquery-cookie 并参考。
然后,就像将if
语句更改为:
if ($.cookie("myCookie") !== undefined)
{
$(".myContent").hide();
}
如果您愿意,也可以使用$.cookie
来设置Cookie; README.md有例子。
答案 1 :(得分:1)
我给你举了一个例子:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">
$.cookie('myCookie', 25);
$(document).ready(function(){
if ($.cookie('myCookie') >= 0) {
$('.myContent').hide();
}
});
</script>
</head>
<body>
<div class="myContent">
hide this content if the cookie is set
</div>
</body>
</html>
此示例隐藏div,因为25&gt; 0
在其他情况下:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">
$.cookie('myCookie', 25);
$(document).ready(function(){
if ($.cookie('myCookie') >= 26) {
$('.myContent').hide();
}
});
</script>
</head>
<body>
<div class="myContent">
hide this content if the cookie is set
</div>
</body>
</html>
现在我改变了if条件和它显示的div myCookie = 25,它小于26(所以它在两种情况下都有效)。
------------------------------ EDITED ---------------- ------------------
Javascript版本:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/"; //replace this line
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
Javascript创建cookie调用:
createCookie('ppkcookie','testcookie',7) //name_of_cookie,value,num_days
阅读cookie:
var x = readCookie('ppkcookie1')
此处有完整说明:http://www.quirksmode.org/js/cookies.html
在createCookie函数中:
document.cookie = name+"="+value+expires+"; path=/"; //replace this line
//with this one adding domain
document.cookie = name+"="+value+expires=" + ";domain=.example.com;path=/";
Saludos;)