How to store data as a url parameter using javascr

2019-07-18 03:48发布

I have a tabbed navigation menu and I have created hashed URLs for each tab. In one tab I have multiple information cards and a check box in the top right hand corner of each card. when this check box is checked the card's background color changes.

My objective is that when the page is refreshed or sent as a link the cards that have been checked remain checked along with the changed background color. Any help would really be appreciated.

2条回答
在下西门庆
2楼-- · 2019-07-18 04:02

I think you need to use the combination of url parameter and localStorage to achive both refreshing and link requirements.

Lets say a user open your site with this url:

www.mysite.com/mypgae?tab=tab1&card1=checked&card2=unchecked&card3=checked

You read these parameters in your page javascript and will goto tab1 and mark card2 and card3 as checked and card2 as unchecked

now lets assume that the user changes the tab and some cards, you should store these changes in the localStorage and next time the user refreshed the page, at first you check the localStorage if it was empty you go for the url. But, if localStorage was not empty you give priority to localStorage and apply changes based on localStorage instead of url.

That is the only way that comes to my mind to support both url and local changes at the same time.

查看更多
戒情不戒烟
3楼-- · 2019-07-18 04:25

You can use a function like this:

function dataToQueryString(data){
    var encoded = [];

    for(var key in data){
        // skip prototype properties
        if(!data.hasOwnProperty(key)) continue;

        // encode string properly to use in url
        encoded.push(key + '=' + encodeURIComponent(data[key]));
    }

    return '?' + encoded.join('&');
}

And use it like:

data = {
    id: 1,
    name: "John Doe"
}

url = url + dataToQueryString( data );

Or more specific for your case:

function storeCardsInQueryString(cards){
    var encoded = [];

    for(var i = 0; i < cards.length; i++){
        encoded.push('cards[]=' + cards[i]);
    }

    return '?' + encoded.join('&');
}

And use it like:

cards = [ 1, 7, 21, 22, 53 ];

url = url + storeCardsInQueryString( cards );
查看更多
登录 后发表回答