Question

So I previously asked similar question but few hours later when I tried to use it I couldn't exactly figure out how to use it. I was told the following:

$(element).removeClass('active');
$(element).data('removed-class', 'active');

Further it can be fetched using

var removeClass = $(element).data('removed-class');

So what exactly would be the most "clean" way to get it to function?

So basically, if I have 7 <li> rows, and randomly 3 of the <li> have the class "active".

Now, if I execute an function that performs to remove all the "active" classes from the <li> with $("li").removeClass("active") for example, how can I now restore the same "active" <li> classes that had the class removed?

Cheers

Était-ce utile?

La solution

Give this a shot, and see if it fits the bill.

var $listItems = $('li','#wrapper');

function clsToData (elements, cls) {
    $(elements).each(function(){
        var $this = $(this);
        if($this.hasClass(cls)){
            $this.removeClass(cls).data('removed-class',cls);
        }
    });
}

function restoreRemovedClasses (elements) {
    $(elements).each(function(){
        var $this = $(this);
        $this.addClass($this.data('removed-class'));
    });
}

$('button','#buttons').on('click',function(){
    var $this = $(this);
    switch ($this.attr('id')){
        case "button1":
            clsToData($listItems,'active');
            break;
        case "button2":
            restoreRemovedClasses ($listItems);
            break;
    }
});

http://jsfiddle.net/rA5aF/

Autres conseils

$("li").addClass($("li").data('removed-class'));

Except you should probably target the appropriate elements, not every li element in the DOM.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top