“remember” div's style on click (set a cookie) - jquery and jquery cookie plugin

做~自己de王妃 提交于 2019-12-11 18:35:58

问题


I have a group of divs with mouseenter, mouseleave and click events.

var originalAttributes = $('.aaa').attr('style');
$('.aaa').mouseenter(function () {
    $(this).css('background', '#aaaaaa');
    $(this).css('border', 'solid 1px red');
});
$('.aaa').mouseleave(function () {
    $(this).css('background','blue');
});
$('.aaa').click(function () {
    var $this =  $(this);
    update_x1(this);
    $this.off('mouseenter mouseleave');
});
$('#save').click(function () {
    $.cookie({ expires: 30 });
});
$('#clear').click(function () {
    $('.aaa').attr('style',originalAttributes);
});

http://jsfiddle.net/z8KuE/24/

How "save" and "clear" functionality can be achieved in this function and with the usage of jquery cookie plugin?

Click on "save" should "remember" the div's current style, and click on "clear" should reset the style to original and clear the cookie (or re-write).

edit: solved by Shimon Rachlenko - http://jsfiddle.net/z8KuE/31/


回答1:


Here is the code for save and clear buttons:

$('#save').click(function () {
    $('.aaa').each(function(){
        var d = $(this),
        id = d.attr('id'),
        style = d.attr('style');
        if (style != originalAttributes){   //style changed
            $.cookie('aaaStyle' + id, style, { expires: 30 });
        }
    });

});
var originalAttributes = "position: relative; left: 50px; top: 30px; width: 300px; height: 50px; background: #222222";
$('#clear').click(function () {
    // unset changes
    $('.aaa').attr('style',originalAttributes);
});

See fiddle



来源:https://stackoverflow.com/questions/19092425/remember-divs-style-on-click-set-a-cookie-jquery-and-jquery-cookie-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!