基于cookie和Toggle复选框切换类

发布于 2025-01-23 15:30:31 字数 980 浏览 4 评论 0原文

我在浏览器中成功设置了一个cookie,以便cookie在检查时返回cookie value true ,并在未选中时false。此cookie在复选框的每次点击中来回更改。

这是我需要做的:

  1. 在页面加载时,它读取cookie,如果cookie值为true,则运行addClass。如果cookie是false,则运行removeclass
  2. 如果手动检查了复选框,它将运行addClass
  3. 如果复选框是手动未检查的,则运行removeclass
  4. 切换后,它需要立即运行添加或删除类,而不是等到页面加载后。

这是我所拥有的,并且没有错误的错误。它现在正在工作,但是页面加载后有一个滞后。如何修复它以删除滞后?

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:

  1. On page load, it reads cookie, and if cookie value is true then it runs addClass. If cookie is false, then it runs removeClass.
  2. If the checkbox is manually checked, it runs addClass.
  3. If the checkbox is manually unchecked, it runs removeClass.
  4. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱花细雨 2025-01-30 15:30:31

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. use let or const instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文