开发者

jQuery - Change class on click and remember via cookie

Hey folks. I am trying to set up a page where if you click on a link the class will change. One step further this would have to be stored in a cookie. Each A tag has a unique id.

For example, below is my example link:

<a href="#" id="unique1" class="up">Link text</a>

When a user clicks the link then the class would need to be changed to "down" AND a cookie would have to be stored for one week remembering this click. Any future v开发者_如何学Cisits to that page then would have to refer to the cookie and set the class accordingly if the link was previously clicked.

My knowledge on javascript and jQuery is minimal.. this is just above my head. Any suggestion on how to make this work?


I would use this plugin to effect this:

http://code.google.com/p/cookies/

The code could be something like:

    // set default options
    // expires date
    var $todayDate = new Date();
    var $expireDate = ($todayDate.getDate() + 7) + '/' + $todayDate.getMonth() + '/' + $todayDate.getFullYear();

        $.cookies.setOptions({
            expiresAt: $expireDate;
            });


    // click functionality
        $('#unique1').click(function(){

           var $this = $(this);

           $this.removeClass('up').addClass('down');

           var $thisClass = $this.attr("class");

           $.cookies.set('ckClass', $thisClass);

           return false;

        });

To check the cookie value and make sure that class is present use something like:

var $ckVal = $.cookies.get('ckClass');
    if ($ckVal) {
        if ($ckVal == 'up') {
            $('#unique1').attr('class', '').addClass('up');
        } else {
            $('#unique1').attr('class', '').addClass('down');}
    }


Sure you can change the class to down on a click.

$(".up").click(function(evt){ $(event.target).removeClass("up").addClass("down"); });

Cookie handling in JS? Read up a bit on that. You will essentially want to set the unique ID as an array / list of them inside the cookie. Then on page load do this.

// list = ['#unique1', '#unique2' ... '#unique-n'];
for(var id in list)
{
    $(id).removeClass("up").addClass("down");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜