gpt4 book ai didi

javascript - 添加 cookie 后 Jquery 切换不起作用

转载 作者:行者123 更新时间:2023-11-29 15:20:51 26 4
gpt4 key购买 nike

试图通过添加 cookie 来维持最后的切换状态 https://github.com/carhartl/jquery-cookie .这是我尝试做的。

<html>
<head>
</head>
<body>
<p>Lorem ipsum.</p>
<button>Toggle</button>
</body>
</html>

然后是 jQuery 和 Javascript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
if ($.cookie){
$("p").toggle(!(!!$.cookie("toggle-state")) || $.cookie("toggle-state") === 'true');
}

$("button").on('click', function(){

$("p").toggle();
$.cookie("toggle-state", $("p").is(':visible'), {expires: 1, path:'/'});
});
});
</script>

Fiddle

我希望 cookie 记住开关的最后状态,无论是隐藏还是显示,它已经存在了一天。

不工作。为什么?

最佳答案

您没有关闭您的第一个点击事件,因为错误您的代码将无法正常运行。

$("button").click(function() {

当您关闭它时一切正常:enter image description here

工作代码:

$(document).ready(function() {
$("button").click(function() {
if ($.cookie){
$("p").toggle(!(!!$.cookie("toggle-state")) || $.cookie("toggle-state") === 'true');
}
});

$("button").on('click', function() {
$("p").toggle();
$.cookie("toggle-state", $("p").is(':visible'), {expires: 1, path:'/'});
});
});

关于javascript - 添加 cookie 后 Jquery 切换不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43888781/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com