Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
73 views
in Technique[技术] by (71.8m points)

javascript - Is this the correct way to use localStorage?

I want to be able to switch themes using a element. The themes are stored in different .css files and by picking a different <option>, I can in turn pick a different theme. However, switching pages switches themes back to whatever I have currently written into my actual template. Here is my .js file:

$(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"));
        }
    });
});

And here is my template:

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

I figure my error has something to do with how my use of localStorage is being handled, but I'm not sure how.

question from:https://stackoverflow.com/questions/65893679/is-this-the-correct-way-to-use-localstorage

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You code seems [for me] very complicated

just do

<div style="text-align: center">
  <select class="form-control" name="select" id="select">
    <option value="/static/styles.css"     > Original      </option>
    <option value="/static/stylesdark.css" > Dark Mode      </option>
    <option value="/static/stylescyber.css"> Cyber Mode      </option>
    <option value="/static/stylesfire.css" > Fire & Brimstone </option>
  </select>
</div>
const theSelect = document.querySelector('#select')

theSelect.value = localStorage.getItem('theme') || theSelect.options[0].value 

theSelect.onchange = e =>
  {
  localStorage.setItem('theme', theSelect.value)
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...