所以,我有这个javascript代码:
function check(x) {
elements = document.getElementsByClassName(x);
for (var i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = "yellow";
}
}
使用此代码,我可以更改html页面中任何类的任何内容的backgroundColor。
我有很多带有不同类的“a”标签,例如:
<a class="1" onclick="check(this.className)">text 1</a>
<a class="2" onclick="check(this.className)">text 2</a>
<a class="3" onclick="check(this.className)">text 3</a>
<a class="4" onclick="check(this.className)">text 4</a>
当我点击时,我可以改变背景颜色。
我的问题是当我尝试在localStorage中保存此更改时。我想在加载页面上保存背景颜色更改,检查用户是否单击以更改背景颜色,例如:
function check(x) {
elements = document.getElementsByClassName(x);
for (var i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = "yellow";
}
if (localStorage[x] != "yellow") {
elements[i].style.color = "yellow";
localStorage[x] = "yellow";
} else {
elements[i].style.color = "";
localStorage[x] = "";
}
}
window.onload = function() {
if (localStorage[x]) {
elements[i].style.backgroundColor = localStorage[x];
}
}
这是我发现突出文字的方式,用户认为是在进行交流并且他想要标记,但这不起作用。 有人可以帮我这个吗?
答案 0 :(得分:1)
您可以执行类似
的操作function check(x) {
var elements = document.getElementsByClassName(x);
for (var i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = "yellow";
}
var colors = localStorage.getItem('colors');
colors = colors ? colors.split(',') : [];
if (colors.indexOf(x) == -1) {
colors.push(x);
localStorage.setItem('colors', colors.join(','));
}
console.log(colors, localStorage.getItem('colors'))
}
window.onload = function () {
var colors = localStorage.getItem('colors');
if (colors) {
colors = colors.split(',');
for (var i = 0; i < colors.length; i++) {
check(colors[i])
}
}
}
演示:Fiddle
答案 1 :(得分:0)
将所有内容放入for循环中:
function check(x) {
elements = document.getElementsByClassName(x);
for (var i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = "yellow";
if (localStorage[x] != "yellow") {
elements[i].style.color = "yellow";
localStorage[x] = "yellow";
} else {
elements[i].style.color = "";
localStorage[x] = "";
}
}
}
window.onload = function() {
var elements = document.getElementsByClassName("a");
for (var i = 0; i < elements.length; i++) {
if (localStorage[x]) {
elements[i].style.backgroundColor = localStorage[x];
}
}
}
请注意,我在第二个循环中有document.getElementsByClassName("a")
,替换&#34; a&#34;与您的所有标签共享的任何类别。