javascript - 使用 JavaScript 选择 CSS 主题
问题描述
我正在运行一个仅限本地的站点,而不是在网络服务器上。
我有几个用户可选择的 CSS 样式。如果直接在页面上,则使用此代码非常有效。
<div class="themeselect">
<table><tr>
<td><a href="#" onclick="localStorage.setItem('style','screen');location.reload()"><i class="far fa-sun"></i></a></td>
<td><a href="#" onclick="localStorage.setItem('style','highcontrast');location.reload()"><i class="far fa-moon"></i></a></td>
</tr></table>
</div>
我想将该带有<script src="js/themeselect.js"></script>
语句的 HTML 注入到带有外部 JS 文件的页面上。我已经尝试过了,但是单击链接没有任何作用。我认为这可能与单引号和/或双引号有关,但我似乎尝试了它们的每一种组合,但我无法弄清楚。
document.write("<div class='themeselect'>");
document.write("<table><tr>");
document.write("<td><a href='#' onclick='localStorage.setItem('style','screen');location.reload()'><i class='far fa-sun'></i></a></td>");
document.write("<td><a href='#' onclick='localStorage.setItem('style','highcontrast');location.reload()'><i class='far fa-moon'></i></a></td>");
document.write("</tr></table>");
document.write("</div>");
解决方案
逃脱它!
检查我如何写第 3 行和第 4 行:
document.write("<div class='themeselect'>");
document.write("<table><tr>");
document.write("<td><a href='#' onclick=\"localStorage.setItem('style','screen');location.reload()\"><i class='far fa-sun'></i></a></td>");
document.write("<td><a href='#' onclick=\"localStorage.setItem('style','highcontrast');location.reload()\"><i class='far fa-moon'></i></a></td>");
document.write("</tr></table>");
document.write("</div>");
推荐阅读
- scala - Kafka Streams 时间窗口聚合
- python - 如何使用熊猫从三列创建时间值
- python - 我正在计算 Pytorch 神经网络回归模型中的平均 RMSE 损失。这是对的吗?
- java - 具有依赖关系的 Spring Boot 项目中的属性层次结构
- mysql - 从与条件匹配的任一表中的值连接的表中选择匹配的行
- javascript - 我用于映射的 javascript 代码按字符拆分单词,并且不会读取输入中的整个单词
- orocommerce - 将域和 ssl 添加到 orcommerce b2b 网站后,我无法再添加项目
- python - AWS/Python:查看 SQS 消息
- reactjs - TypeScript/React 中的枚举索引签名
- javascript - 如何将拆分函数与匹配函数一起使用