【发布时间】:2021-04-29 18:49:31
【问题描述】:
我希望能够使用元素切换主题。主题存储在不同的 .css 文件中,通过选择不同的 <option>,我可以依次选择不同的主题。但是,切换页面会将主题切换回我当前写入实际模板的任何内容。这是我的 .js 文件:
$(function() {
var theme = $("#theme");
var getTheme = localStorage.getItem("theme");
$("#select option:selected").each(function() { /* Switch on-change function */
if (getTheme == $(this).data("theme")) {
theme.attr("href", getTheme); /* Set the theme of the page to whatever theme applies to this option */
console.log($(this).data("theme"));
}
else {
theme.attr("href", $(this).data("theme"));
localStorage.setItem("theme", $(this).data("theme")); /* Store the choice into local storage; should persist upon page reload */
console.log($(this).data("theme"));
}
});
});
这是我的模板:
<div style="text-align: center">
<select class="form-control" name="select" id="select">
<option selected value="original" data-theme="/static/styles.css">Original</option>
<option value="darkmode" data-theme="/static/stylesdark.css">Dark Mode</option>
<option value="cybermode" data-theme="/static/stylescyber.css">Cyber Mode</option>
<option value="fire" data-theme="/static/stylesfire.css">Fire & Brimstone</option>
</select>
</div>
我认为我的错误与我对 localStorage 的使用方式的处理方式有关,但我不确定如何处理。
【问题讨论】:
-
我没有看到你在
$data()中设置了theme -
@Rojo 你的意思是
var theme = $("#theme");? -
@Barmar 不,我的意思是
$(this).data("theme") -
来自 HTML 中的
data-theme="..."。 -
我想你想要
if (getTheme == $(this).val())
标签: javascript html css local-storage