我的问题是,通过单击按钮来设置cookie是行不通的。我用3种不同的方法测试了它。
HTML:
<!DOCTYPE html>
<html dir="ltr">
<head> [...]
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script src="/cookies/js/jquery.cookie.js"></script>
<script>
document.getElementById('btnSetCookie').onclick = function () {
$.cookie('cookie-1', 'true');
alert('You have set the cookie: ' + jQuery.cookie('cookie-1'));
});
$(function () {
$("#btnSetCookie").click(function () {
jQuery.cookie('cookie-2', 'true');
alert('You have set the cookie: ' + jQuery.cookie('cookie-2'));
});
});
$(document).ready(function () {
$("#btnSetCookie").on('click', function () {
$.cookie('cookie-3', 'true');
alert('You have set the cookie: ' + jQuery.cookie('cookie-3'));
});
});
</script>
</head>
<body> [...]
<button id="btnSetCookie">set cookie</button> [...]
</body>
</html>知道我犯了什么错吗?
发布于 2018-03-02 16:28:09
这不适用于您的原因是,如果没有在服务器上运行,则无法设置cookie。换句话说,如果您在本地使用file://,在浏览器中为文件提供服务,则它根本无法工作。
您的第二个和第三个选项运行良好。我会清理它们,并一致地使用$或jQuery,但是在服务器上运行时两者都可以工作。
下面是代码工作的演示。
$(document).ready(function () {
$("#btnSetCookie").on('click', function () {
$.cookie('cookie-3', 'true');
alert('You have set the cookie: ' + $.cookie('cookie-3'));
});
});您还可以考虑使用最新版本的jQuery,以及您正在使用的插件(您使用的版本不再维护)。事实上,新版本的插件不再依赖于jQuery。
https://stackoverflow.com/questions/49070213
复制相似问题