刷新页面时保存用户的选择 [英] Saving user's selection when refreshing the page

查看:121
本文介绍了刷新页面时保存用户的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有一个显示不同团队数据的页面。



我有一些数据可供用户点击以使其成为开或关 状态,每个都显示不同的图标。它基本上就像一个清单,只是没有物理复选框。

我想记住哪个复选框已勾选,即使在用户刷新页面或关闭浏览器并稍后返回。



我听说 localStorage 是一个不错的选择,但我不是确定如何在像我这样的情况下使用它。



目前我有这样的代码:

  team1 = {
information1:{
name:tom,
age:34
},
information2:{
name:bob,
age:20
},
};

2= {
information1:{
name:betsy,
age:27
},
information2:{
name:brian,
age:10
},
};
$ b $(document).ready(function(){

$(#displayObject1)。on(click,function(){
switchData (team1);
});

$(#displayObject2)on(click,function(){
switchData(team2);
});
$(#table)。on(click,.on,function(){
$(this).removeClass(on);
$(this).addClass(off);
});
$(#table)。on(click,.off,function(){
$(this).addClass(on);
$(this).removeClass(off);
});
});


函数switchData(object){
$(#table)。contents(div)。remove();
if(!('object')){
var rows = [];
Object.keys(object).forEach(function(key){
if(key!='rows'){
rows.push($('< div class =row on>'+ object [key] .name +'< / div>'));
}
});
object.rows = rows;
}
object.rows.forEach(function(row){
$('#table')。append(row);
});
}

这使得行代表团队。当用户在浏览器会话期间查看不同团队时,这些行将保留其颜色突出显示。



这是我的HTML:

 < div id =displayObject1> 
< span>显示物件1< / span>
< / div>
< div>< hr>< / div>
< div id =displayObject2>
< span>显示对象2< / span>
< / div>
< div id =table>
< / div>

还有一些CSS用于显示哪些列表项是on和off。

  .on {
background-color:green;
}
.off {
background-color:red;
}

页面如何记住颜色突出显示?

解决方案

如果您想使用本地存储,以使浏览器会话中的团队列表状态保持不变,您必须保持状态的逻辑表示,并在状态发生更改时将其保存为字符串。 p>

JSON.stringify 可让您用JSON字符串编码JavaScript对象。例如,每当修改名为 pageState 的全局对象时,您可以调用类似以下的函数:

  function savePageState(){
localStorage.setItem('pageState',JSON.stringify(pageState));
}

要在页面加载中检索页面状态,可以这样做:

  pageState = JSON.parse(localStorage.getItem('pageState')); 
if(pageState === null){
pageState = {
teams:teams
};
savePageState();
} else {
teams = pageState.teams;

如果 pageState wasn保存在前一个会话中,现在创建并保存到本地存储。否则,我们会参考 pageState 查看我们可以用来恢复团队列表以前出现的数据。



代码示例假定全局对象 teams 包含与页面状态相关的信息。您可以将更多属性添加到页面状态对象以存储更多信息。例如,要记住当前显示哪个团队,您可以这样做:

然后,您可以参阅 pageState.showTeam 你可能是这样初始化页面内容:

  if(teamName == pageState.showTeam){
showTeam(teamName);
$(label).addClass('selected');
}

我已经制作了一个演示此方法的页面。我不能将它作为代码片段包含在我的答案中,因为 localStorage 是沙盒,但您可以在此访问该页面:

http://michaellaszlo.com/so/click-rows/



我已经重组了您的团队数据以启用动态页面初始化。现在每个团队对象都包含一个人物对象数组。



当用户点击团队成员的名字时,CSS class selected 在HTML元素上切换,并通过切换其选定的属性更新相应的person对象:

  function memberClick(){
$(this).toggleClass('selected');
this.person.selected =(this.person.selected?false:true);
savePageState();
};

showTeam 函数检查一个人的 selected 属性,并在适当时添加CSS类 selected 。这可以从上次会话中恢复页面的外观。


I currently have a page that displays data for different teams.

I have some data that the user can click on to make it an "on" or "off" state, showing a different icon for each. It's basically like a checklist, just without the physical checkboxes.

I would like to remember which of the "checkboxes" have been ticked, even after the user refreshes the page or closes the browser and returns later.

I have heard that localStorage is a good option, but I'm not sure how to use it in a situation like mine.

Currently I have this code:

team1 = {
    "information1": {
        "name": "tom",
        "age": "34"
    },
    "information2": {
        "name": "bob",
        "age": "20"
    },
};

team2 = {
    "information1": {
        "name": "betsy",
        "age": "27"
    },
    "information2": {
        "name": "brian",
        "age": "10"
    },
};

$(document).ready(function() {

    $("#displayObject1").on("click", function() {
        switchData(team1);
    });

    $("#displayObject2").on("click", function() {
        switchData(team2);
    });
    $("#table").on("click", ".on", function() {
        $(this).removeClass("on");
        $(this).addClass("off");
    });
    $("#table").on("click", ".off", function() {
        $(this).addClass("on");
        $(this).removeClass("off");
    });
}); 


function switchData(object) {
    $("#table").contents("div").remove();
    if (!('rows' in object)) {
        var rows = [];
        Object.keys(object).forEach(function (key) {
            if (key != 'rows') {
                rows.push($('<div class="row on">' + object[key].name + '</div>'));
            }
        });
        object.rows = rows;
    }
    object.rows.forEach(function (row) {
        $('#table').append(row);
    });
}

This makes rows to represent a team. The rows are retained with their color highlighting when the user looks at different teams during a browser session.

This is my HTML:

<div id="displayObject1">
    <span>Display object 1</span>
</div>
<div><hr></div>
<div id="displayObject2">
    <span>Display object 2</span>
</div>
<div id="table">
</div>

And some CSS to show which list items are "on" and "off".

.on {
  background-color: green;
}
.off {
  background-color: red;
}

How can the page remember the color highlighting?

解决方案

If you want to use local storage to make the state of the team listings persist across browser sessions, you have to maintain a logical representation of the state and save it as a string whenever the state changes.

JSON.stringify lets you encode a JavaScript object in a JSON string. For example, you can call a function like the following whenever you modify a global object named pageState:

function savePageState() {
  localStorage.setItem('pageState', JSON.stringify(pageState));
}

To retrieve the page state on page load, you can do something like this:

pageState = JSON.parse(localStorage.getItem('pageState'));
if (pageState === null) {
  pageState = {
    teams: teams
  };
  savePageState();
} else {
  teams = pageState.teams;
}

If pageState wasn't saved in a previous session, it is now created and saved to local storage. Otherwise, we consult pageState for data that we can use to restore the previous appearance of the team listings.

This code sample works on the assumption that the global object teams contains information relevant to the page state. You can add further properties to the page-state object to store more information. For example, to remember which team is currently displayed, you could do:

pageState.showTeam = teamName;

Then you can consult pageState.showTeam when you're initializing the page contents, perhaps like this:

if (teamName == pageState.showTeam) {
  showTeam(teamName);
  $(label).addClass('selected');
}

I have made a page that demonstrates this approach. I can't include it in my answer as a snippet because localStorage is sandboxed, but you can access the page here:

http://michaellaszlo.com/so/click-rows/

I've reorganized your team data to enable dynamic page initialization. Now each team object contains an array of person objects.

When the user clicks on a team member's name, the CSS class selected is toggled on the HTML element and the corresponding person object is updated by toggling its selected property:

function memberClick() {
  $(this).toggleClass('selected');
  this.person.selected = (this.person.selected ? false : true);
  savePageState();
};

The showTeam function checks a person's selected property when it's building its HTML representation, and adds the CSS class selected if appropriate. This is what makes it possible to restore the visual appearance of the page from the last session.

这篇关于刷新页面时保存用户的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆