如何将属性保存在html中(无Cookie - 只是本地存储)
问题描述:
我有一个日历,日历中可点击。每次点击它都会改变颜色(白色默认,红色和绿色 - 环形)。如何将属性保存在html中(无Cookie - 只是本地存储)
<script type="text/javascript">
function inArray(needle, haystack) {
if (!needle || !haystack) {
return false;
}
else {
var notFound = -1;
for (var i = 0, len = haystack.length; i < len; i++) {
if (haystack[i] == needle) {
return i;
}
}
return notFound;
}
}
function colorToggle(el, colors) {
if (!el) {
return false;
}
else {
var colors = colors || [
'rgb(255, 0, 0)',
'rgb(0, 255, 0)',
'rgb(0, 0, 255)'],
wGCS = window.getComputedStyle,
curColor = wGCS(el, null).backgroundColor;
var pos = inArray(curColor, colors);
if (pos > -1 && pos < (colors.length - 1)) {
el.style.backgroundColor = colors[inArray(curColor, colors) + 1];
}
else if (pos > -1 && pos == (colors.length - 1)) {
el.style.backgroundColor = colors[0];
}
}
}
var buttons = document.querySelectorAll('button.colorToggle');
for (var i = 0, len = buttons.length; i < len; i++) {
buttons[i].style.backgroundColor = 'rgb(255, 255, 255)';
buttons[i].onclick = function() {
colorToggle(this, ['rgb(255, 255, 255)','rgb(0, 255, 0)','rgb(255, 0, 0)']);
};
}
</script>
现在,我想保持的颜色后刷新/重新打开index.html页面。
谢谢你的帮助。
答
您首先需要为每个元素分配一个id
或data-
属性,以便您可以在重新加载页面时将存储的颜色值与它们分配的元素相关联。作为一个例子,让我们使用每个单元格的ISO日期作为标识符。
日历中的每个日期的单元格可能是这样的:
<button data-date="2015-09-01" class="colorToggle">1</button>
<button data-date="2015-09-02" class="colorToggle">2</button>
然后,在colorToggle
您可以将数据保存到localStorage
像这样:
localStorage.setItem(el.getAttribute("data-date"), el.style.backgroundColor);
在页面加载,你可以重置首先检索节点,然后尝试从localStorage
中提取颜色并将颜色重新分配。
var nodes = Array.prototype.slice.call(document.querySelectorAll("[data-date]"));
nodes.forEach(function (node) {
var date = node.getAttribute("data-date");
var color = localStorage.getItem(date);
if(color) {
node.style.backgroundColor = color;
}
});
只是最后一点,我强烈建议包括ES5 Array.prototype方法的polyfill。这会让您在上面的示例中访问forEach
,并允许您用Array.prototype.indexOf
替换inArray
。