samedi 30 septembre 2017

JS if / else if / not working correctly

I am having some difficulties in getting this work, and can't figure out what is causing the issue. Basically I am checking if local storage has item 3-step, if not create it and give it the value of 1. By having the value of 1 then add class "selected" to first LI, if the value is 2 then add class "selected" to second LI, and so on - this is happening on click of buttons and it is saving the values to the local storage correctly.

However when the page is refreshed and it does the check to see which li to add the class of "selected", it does not work. Only works if the value is 1, then it will add the class to the first LI, the other LIs will not work for some reason.

 var ls;
 if( localStorage.getItem('3-step') == null ) {
    var ls = 1;
    localStorage.setItem('3-step', ls);
 } else {
    var ls = parseInt( localStorage.getItem('3-step') );
    if( ls == 1 ) {
       $('#li-one').addClass('selected');
    } else if ( ls == 2 ) {
       $('#li-two').addClass('selected');
    } else if ( ls == 3 ) {
       $('#li-three').addClass('selected');
    }
 }
.selected {
   background: red;
}
<script src="http://ift.tt/notapP"></script>
<ul id="ul">
   <li id="li-one" class="section">
      Stuff One
   </li>

   <li id="li-two" class="section">
      Stuff Two
   </li>

   <li id="li-three" class="section">
      Stuff Three
   </li>
</ul>

But in the js script during the check to see what value is in the local storage, if I make the div id all to #li-one it works. Meaning if it's –– if(ls == 3){ $('#li-one').addClass('selected') –– this works, but if it's –– if(ls == 3){ $('#li-two').addClass('selected') OR if(ls == 3){ $('#li-three').addClass('selected') –– this does not work.

ALSO, I cannot get the example here to work at all – i guess localstorage is not allowed.

Thank you so much,

Sergio

Aucun commentaire:

Enregistrer un commentaire