jQuery Cookieプラグインを見てみましょう。これにより、Cookie の操作が非常に簡単になります。
Cookie の作成は次のように簡単です。
$.cookie('the_cookie', 'the_value');
要素を Cookie に保存する場合は、もう少し作業が必要になります。要素の ID が静的な場合は、それらを配列に格納してから、次を使用して Cookie に格納できますJSON.stringify
。
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));
});
要素を取得するには、次を使用する必要がありますJSON.parse
。
var elements = JSON.parse($.cookie('elements'));
for(var i = 0; i < elements.length; i++) {
$("#" + elements[i]).addClass('is-visited');
}