简体   繁体   中英

CSS theme select with JavaScript

I am running a local-only site, not on a webserver.

I have a couple CSS styles that are user-selectable. Using this code works perfectly if it's directly on the page.

<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>

I want to inject that HTML with a <script src="js/themeselect.js"></script> statement onto the page with an external JS file. I have tried this, but clicking the links doesn't do anything. I thought it might have something to do with the single and/or double quotes, but I've tried seemingly every combination of them, and I can't figure it out.

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>");

if you want to inner text between body tag or container element:

document.body.innerHTML = "<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>"

replace " to ',it work xD

Escape it !!!

Check how i wrote 3rd and 4th line:

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>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM