我有这段代码,可以在用户单击时更改 td 的背景颜色,并在用户再次单击时更改为另一种颜色,我想要做的是将更改保存在本地存储中,以便当用户刷新页面时更改遗迹。有谁知道该怎么做吗?
这是 jsfiddle: enter link description here
最佳答案
您可以轻松使用localStorage
去做这个。设置localStorage
当您更改状态然后加载页面时,获取 localStorage
并重置每个 td
他们之前的样子是基于localStorage
值:
这是my update for your JSFiddle 。另外,我只更改了 JavaScript,因此这里是 JavaScript 代码:
//Get all of the tds:
var tds = $("td");
//Loop through all tds:
for (var i = 0; i < tds.length; i++) {
//Get the previous state of the td:
var prevState = localStorage.getItem("state"+i);
console.log(prevState);
//If prevState is null, set it to "first":
if (prevState === null) {
localStorage.setItem("state"+i, "first");
}
//Otherwise, restore prevState:
else {
//Get the td:
var cell = $(tds.get(i));
//Depending on prevState:
switch (prevState) {
case "first":
//Do nothing if it's in the first state because that's the default.
break;
case "second":
//Add the class "red" if it's in the second state:
cell.addClass("red");
break;
case "third":
//Add the class "yellow" if it's in the third state:
cell.addClass("yellow");
break;
default:
//If it's something else, set it to "first":
localStorage.setItem("state"+i, "first");
prevState = "first";
break;
}
//Set cell's data-state to prevState:
cell.data("state", prevState);
}
}
tds.click(function () {
var cell = $(this),
state = cell.data('state') || 'first';
switch (state) {
case 'first':
cell.addClass('red');
cell.data('state', 'second');
break;
case 'second':
cell.addClass('yellow');
cell.data('state', 'third');
break;
case 'third':
cell.removeClass('red yellow');
cell.data('state', 'first');
break;
default:
break;
}
//Update state:
state = cell.data("state");
//Get the index of the td:
var index = tds.index(cell);
//Set localStorage using index and state:
localStorage.setItem("state"+index, state);
});
关于javascript - 如何将表格单元格中的背景颜色更改保存在本地存储中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32167982/