简体   繁体   中英

SessionStorage.getitem not working when loading page

I am having an issue trying to use storagesession. I have gotten it to work, but as soon as I insert some ifthen logic, it breaks. Below is the working code. The bottom code is when I update the window.onload function that makes it break. Does anybody know why its breaking and how I can fix this? I am using only html/javascript and no server is being used. Thanks so much!

<!DOCTYPE html>
<!-- saved from url=(0014)about:internet -->
<html lang="en">
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="container">

<ul class="vertical-nav">

<li><a href="">Fruit</a>
<ul class="sub-menu">
<li><a href="test.html" onclick="ChangeToApple()">Apple</a></li>
<li><a href="test.html" onclick="ChangeToGrape()">Grape</a></li>
</ul>
</li>
</ul>

<div id="ShowDept">

</div>
</div>
</body>
<script>

  window.onload = function() {
  var x = sessionStorage.getItem("Dept");


document.getElementById("ShowDept").innerHTML = x;
 }

function ChangeToApple() {
sessionStorage.Dept = "Apple";
}

function ChangeToGrape() {
sessionStorage.Dept = "Grape";
}

 </script>
  window.onload = function() {
  var x = sessionStorage.getItem("Dept");

      if (x = "Apple") {

} else if (x = "Grape") {

}
document.getElementById("ShowDept").innerHTML = x;
 }
var x = sessionStorage.getItem("Dept");

if (x = "Apple") {

} else if (x = "Grape") {

}
document.getElementById("ShowDept").innerHTML = x;

x = "Apple" means "Assign the string 'Apple' to the variable x . It does not check if x equals "Apple" ; use x === "Apple" for that. Because you're doing an assignment in your if statement, you're going to always see Apple in your HTML.

instead of

sessionStorage.Dept = "Apple";

try

sessionStorage.setItem("Dept", "Grape");

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