jQuery: if condition is false, but still executed? [duplicate]

允我心安 提交于 2019-12-10 18:37:24

问题


The following code

  $(document).ready(function(){

    sessionStorage.test = false;  

    alert( sessionStorage.test );

    if ( sessionStorage.test ) {
      alert("I dont care about your conditions!");
    }

  });

produces the following popups:

false

I dont care about your conditions!

even though sessionStorage.test is clearly set to false. Why is that the case? According to this answer https://stackoverflow.com/a/17986241/2311074, this should work. What am I doing wrong? I am using XAMPP - does it maybe have problems with sessionStorage? Here is the complete code of my test file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script >
      $(document).ready(function(){
        sessionStorage.test = false;    
        if ( sessionStorage.test ) {
          alert("I dont care about your conditions!");
        }
      });
    </script>
  </head>
  <body>
    <!-- page content -->
  </body>
</html>

回答1:


The default getter/setter for sessionsStorage are:

sessionStorage.setItem('keyName', 'value');    
sessionStorage.getItem('keyName')

So, for example:

sessionStorage.setItem('test',false);    
if (sessionStorage.getItem('test') != "false") {
   ..........
}

Duplicate Topics:
- sessionStorage setItem returns true or false
- sessionStorage isn't working as expected



来源:https://stackoverflow.com/questions/39127730/jquery-if-condition-is-false-but-still-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!