简体   繁体   中英

HTML5 LocalStorage - how to use it with hyperlinks?

I'm hoping to use HTML5 Local Storage on my web page data so it persists beyond a page refresh.

Here is my code:

<h3 data-target="#colours_filters">Colour</h3>
<ul id="colours_filters">
    <li class="filter-option"><a href="#" data-tax="colours" data-filter=".tag-colours-black-2">Black</a></li>
    <li class="filter-option"><a href="#" data-tax="colours" data-filter=".tag-colours-blue">Blue</a></li>
</ul>

So if I click 'Blue' and/or 'Black', it will store this in LocalStorage ?

Can someone help point me in the right direction?

Thank you :-)

Try first to give unique id to your elements

<h3 data-target="#colours_filters">Colour</h3>
<ul id="colours_filters">
    <li class="filter-option"><a href="#" id='unique_1' data-tax="colours" data-filter=".tag-colours-black-2">Black</a></li>
    <li class="filter-option"><a href="#" id='unique_2' data-tax="colours" data-filter=".tag-colours-blue">Blue</a></li>
</ul>

and then

$(document).ready(function(){

    $('.filter-option a').on('click', function() {

        var isActived = $(this).hasClass('active') == false; 
        var id = $(this).attr('id');

        localStorage.setItem(id,isActived);

        $(this).toggleClass('active'); 
    });

    $('.filter-option a').each(function(){
        var id = $(this).attr('id');

        var hasActiveClass = localStorage.getItem("active");

        if(hasActiveClass != undefined){
            $(this).addClas('active');
        }
    });

});

fiddlejs

Check this Fiddler

$(document).ready(function(){

    $('.filters a').on('click', function() {

        var data_filter = $(this).closest("a").data('filter');
        $(this).addClass('active'); 
        if($(this).hasClass('active')) {
            localStorage.setItem(data_filter,true);
        } else {
            localStorage.setItem(data_filter,false);
        }

    });

   $('.filters a').each(function(){
        var data_filter = $(this).closest("a").data('filter');
        var checked = localStorage.getItem(data_filter);
        if(checked){
            $(this).addClass('active');
        } else {
            $(this).removeClass('active');
        }
    });
});    

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