基于cookie和Toggle复选框切换类
我在浏览器中成功设置了一个cookie,以便cookie在检查时返回cookie value true ,并在未选中时false
。此cookie在复选框的每次点击中来回更改。
这是我需要做的:
- 在页面加载时,它读取cookie,如果cookie值为
true
,则运行addClass
。如果cookie是false
,则运行removeclass
。 - 如果手动检查了复选框,它将运行
addClass
。 - 如果复选框是手动未检查的,则运行
removeclass
。 - 切换后,它需要立即运行添加或删除类,而不是等到页面加载后。
这是我所拥有的,并且没有错误的错误。它现在正在工作,但是页面加载后有一个滞后。如何修复它以删除滞后?
var mytoggle = $.cookie('checkboxValue'); // gets the value saved
if(mytoggle && mytoggle === "true") // (sees if cookie exists and has value of true)
{
$('body').addClass("myclass");
} else // (if cookie doesn't exist or value is false)
{
$('body').removeClass("myclass");
}
基本上,它可以看到是否有一个cookie值true
,如果是的,则添加了类。但是,如果没有cookie或value是false
,它将删除类。如果复选框在页面上切换,则添加或删除了类。
我如何获得该检查cookie并根据cookie值添加或移动类,并在检查或未选中复选框时切换类?
I set a cookie successfully in the browser, so that the cookie returned the cookie value true
when checked, and false
when unchecked. This cookie changes back and forth on every click of the checkbox.
Here's what I need to do:
- On page load, it reads cookie, and if cookie value is
true
then it runsaddClass
. If cookie isfalse
, then it runsremoveClass
. - If the checkbox is manually checked, it runs
addClass
. - If the checkbox is manually unchecked, it runs
removeClass
. - When it is toggled, it needs to run the add or remove class immediately, not wait until after page load.
Here's what I have, and no errors in console. It's working now, but there's a lag after the page load. How can I fix it to remove the lag?
var mytoggle = $.cookie('checkboxValue'); // gets the value saved
if(mytoggle && mytoggle === "true") // (sees if cookie exists and has value of true)
{
$('body').addClass("myclass");
} else // (if cookie doesn't exist or value is false)
{
$('body').removeClass("myclass");
}
Basically, it sees if there's a cookie with value of true
, and if so then adds the class. But if there's no cookie or value is false
, it removes the class. And if the checkbox is toggled while on the page, it adds or removes the class.
How can I get this to check the cookie and add or move class based on the cookie value, and also toggle the class when the checkbox is checked or unchecked?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
cookie是绳子,而不是布尔值。因此,如果(cookie ===“ true”),则应使用
。另外,您无需检查cookie的存在,如果不存在,它将不等于true。
P. S
var
关键字是遗产,被视为不良习惯。使用让
或const
改为使用。Cookie is a string, not a boolean. So, you should use
if (cookie === "true")
. Also, you don't need to check for existence of cookie, it won't be equal to true if not exists.P. S
var
keyword is legacy and considered as a bad practice. uselet
orconst
instead.