【问题标题】:jQuery saving Cookies on a toggled list that use "this"jQuery 将 Cookie 保存在使用“this”的切换列表中
【发布时间】:2023-03-25 15:40:01
【问题描述】:

我正在使用从本网站上的帖子拼凑而成的切换列表显示。他们工作得很好,但我希望他们能够保存 cookie 值。

当您针对单个类/项目(例如“if (myCookie == value) { do stuff to ".myClass"... }”)时,我已经弄清楚了如何让 cookie 发挥作用。但问题是我正在使用一组列表,这些列表会受到使用“$(this)”调用它们的影响。因此,通过类值定位它们是行不通的,因为它们将使用该类定位所有内容。说得通? cookie 需要影响“this”而不是“myClass”。

以下是我为列表拼凑的代码。

// append links to the element directly preceding the element with a class of "toggle"
$(".toggle").prev(".toggleList").append('<a href="#" class="toggleLink" id="collapse"></a>');

// hide all of the elements with a class of 'toggle'
$('.toggle').show();

$('a.toggleLink').click(function() {

    // change the link depending on whether the element is shown or hidden
    if (!$(this).is('.active')) {
        $(this).addClass('active');
        $(this).attr("id" ,"expand");
                    THIS IS WHERE I NEED THE $.COOKIE TO WORK. I NEED IT TO REMEMBER THAT "THIS" IS "EXPANDED" OR THAT THE FOLLOWING LINE IS "COLLAPSED"
    }
    else {
        $(this).removeClass('active'); 
        $(this).attr("id" ,"collapse");
    }

    // toggle the display
    $(this).parent().next('.toggle').toggle();
    return false;
});

只是为了添加... 我确实了解我们在测试站点的其他地方使用过的 cookie 的基本用法。问题是我知道如何使用它们的唯一方法就是像下面那样定位它们……

// cookies
// sidebar state
var sideBar = $.cookie('sideBar');

// Set the user's selection for the left column
if (sideBar == 'collapsed') {
    $('#btnCollapseSidebar').css("visibility" ,"hidden");
    $('#btnExpandSidebar').css("visibility" ,"visible");
    $('#leftCol').css("visibility" ,"hidden");      
    $('#sidebar').css("visibility" ,"hidden");
    $('#rightCol').css("margin" ,"42px 0 0 45px");
};

上面列出的我需要使用它们的方式不能针对单个类,而是针对实际项目(“this”)。当我尝试通过调整上述代码来应用它们时,它会影响我的“.toggle”类的每个实例。 “.toggle”类将在页面上多次使用,并且需要无限次可用。

【问题讨论】:

    标签: jquery list cookies user-interface toggle


    【解决方案1】:

    使用 jQuery Cookie 插件实现起来超级简单。 http://www.electrictoolbox.com/jquery-cookies/

    var CookieOptions = { expires: 7, path: '/' }
    $.cookie("CookieName", "CookieValue", CookieOptions);
    

    通过以下方式获取 cookie:

    $.cookie("CookieName");
    

    【讨论】:

    • 感谢您的输入,但我认为这是我们在其他地方使用 cookie 的方式,我不确定如何将其应用于“this”而不是“.aClass”。那有意义吗?我拥有的代码将在页面上无限次使用“.toggle”。我不能针对“.toggle”,因为它会针对每个实例。我需要能够针对语句的“this”部分。
    • 我不同意这被列为“1”的答案。尽管输入很好,但上面列出的答案对于我已经解决的一个简单问题来说是一个非常简单的解决方案。我遇到的问题是让 cookie 与我正在使用的切换功能一起使用,如我的问题中的代码中所列。
    猜你喜欢
    • 2014-05-22
    • 1970-01-01
    • 2013-08-16
    • 2011-07-04
    • 1970-01-01
    • 2014-08-13
    • 2014-08-16
    • 2019-02-11
    • 1970-01-01
    相关资源
    最近更新 更多