简体   繁体   中英

how to save add or remove classes cookies in my javascript?

I want to save "active" class and "icon" class in cookies. How to do?

html

<div class="changeWrap">
        <span class="switch-male"><a href="javascript:"><i class="glyphicon glyphicon-unchecked"></i> Male</a></span>
        <span class="switch-female"><a href="javascript:" class="active"><i class="glyphicon glyphicon-check"></i><span> Female</span></a></span>
</div>

css

.active{
    color: red;
}

DEMO: http://jsfiddle.net/deqzjefq/2/

First create you cookie:

document.cookie="class=active;gender=male";

Then get value of cookie (name 'class')

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

Then give id to the anchor tags

<div class="changeWrap">
        <span class="switch-male"><a href="javascript:" id='male-anchor'><i class="glyphicon glyphicon-unchecked"></i> Male</a></span>
        <span class="switch-female"><a href="javascript:" id='female-anchor'><i class="glyphicon glyphicon-check"></i><span> Female</span></a></span>
</div>

Check cookie gender:

var gender = getCookie('gender');

if(gender == 'male'{
    document.getElementsById('male-anchor').setAttribute("class", getCookie('class'));
}
else{
    document.getElementsById('female-anchor').setAttribute("class", getCookie('class'));
}

http://jsfiddle.net/k8pbp97k/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM