Jquery Cookie onclick功能

Kik*_*ats 1 cookies jquery function onclick

当用户点击它时,我在jQuery中有隐藏元素的这个功能:

  $(".colabs-image").click(function() {
    $( this ).parent().addClass('is-visited');
  });
Run Code Online (Sandbox Code Playgroud)

我想使用cookie来存储用户点击的元素,并在下次访问时显示.

Whit $(this).parent().attr('href'))我有元素的ID,但我知道如何管理这个任务的cookie.

Viv*_*ath 6

看一下jQuery Cookie插件.它使得使用cookie变得非常简单.

创建cookie非常简单:

$.cookie('the_cookie', 'the_value');
Run Code Online (Sandbox Code Playgroud)

如果要将元素存储在cookie中,则需要更多的工作.如果元素的id是静态的,那么您可以将它们存储在一个数组中,然后使用JSON.stringify以下命令将其存储到cookie中:

var elements = [];
$(".colabs-image").click(function() {
    $(this).parent().addClass('is-visited');
    elements.push($(this).parent().attr('id')); //add the id to the array of elements
    $.cookie('elements', JSON.stringify(elements));
});
Run Code Online (Sandbox Code Playgroud)

要检索元素,您必须使用JSON.parse:

var elements = JSON.parse($.cookie('elements'));
for(var i = 0; i < elements.length; i++) {
    $("#" + elements[i]).addClass('is-visited');
}
Run Code Online (Sandbox Code Playgroud)