单击时将类添加到 ancer 标签并使用 cookie 保存

add a class to an ancer tag on click and save it with cookie

本文关键字:cookie 保存 标签 ancer 添加 单击      更新时间:2023-09-26

直截了当,这是我的简单代码。

 $(".vm-options a").click( function() {
        $(this).addClass("vmselected").siblings().removeClass("vmselected");
    });

<div class="vm-options">
                <a href="#" class="vm-icon vm-list vmselected" id="list">List view</a>
                <a href="#" class="vm-icon vm-grid" id="grid">Grid view</a>
            </div>

现在我需要它记住我的选择,每次我点击"一个href"标签,我怎样才能向它添加cookie。

谢谢。

使用 Javascript Cooke 插件并编写Cookies.set('name', 'value');

或者jQuery Cookie插件并编写$.cookie('name', 'value');

此示例使用 js-cookie 库,您需要将其包含在页面中,如下所示:

<script src="https://rawgit.com/js-cookie/js-cookie/master/src/js.cookie.js"></script>

您可以使用它来存储和检索所选链接的 ID,如下所示:

// Select the currently saved VM at page load
selectVM();
// Do it on click too
$(".vm-options a").click(selectVM);
function selectVM()
{
    var elem = $(this);
    // If the call doesn't come from a click (eg on page load),
    // get the one saved in a cookie or the default one: "#list"
    if(this === window) elem = $('#' + (Cookies.get('selectedVM') || 'list'));
    elem.addClass("vmselected").siblings().removeClass("vmselected");
    // Save it for 7 days
    Cookies.set('selectedVM', elem.id, { expires: 7 });
}

在这里,ID保存在名为selectedVM的cookie中,使用:

Cookies.set('selectedVM', value);

并使用以下方法检索:

Cookies.get('selectedVM');

就是这么简单!