简体   繁体   中英

sessionStorage onclick set value

I have 4 divs, and depending on what the user clicks I want to set a variable on each of them, which I then want to save using sessionStorage.

<div id="1" onClick="sessionStorage.id=1">Select Me as 1</div>
<div id="2" onClick="sessionStorage.id=2">Select Me as 2</div>
<div id="3" onClick="sessionStorage.id=3">Select Me as 3</div>
<div id="4" onClick="sessionStorage.id=4">Select Me as 4</div>

Then on the <head></head> area I've added:

sessionStorage.setItem("id", "");
sessionStorage.getItem("id");
alert(id);

My problem is that the values are not changing and the onclick doesn't see to be storing the new values.

How can I do this right?

Check this demo:

DEMO

  <div id="1" onClick="sessionStorage.id=1">Select Me as 1</div>
  <div id="2" onClick="sessionStorage.id=2">Select Me as 2</div>
  <div id="3" onClick="sessionStorage.id=3">Select Me as 3</div>
  <div id="4" onClick="sessionStorage.id=4">Select Me as 4</div>
  <button onclick="alert(sessionStorage.getItem('id'))">Check Session Value</button>

I guess what you want to do is:

<div id="1" onClick="sessionStorage.setItem('id', '1')">Select Me 1</div>
<div id="2" onClick="sessionStorage.setItem('id', '2')">Select Me 1</div>
<div id="3" onClick="sessionStorage.setItem('id', '3')">Select Me 1</div>
<div id="4" onClick="sessionStorage.setItem('id', '4')">Select Me 1</div>

<button onClick="alert(sessionStorage.getItem('id'))">click to alert</button>

Live Demo

Your html to set the values is fine, but I have no idea why use are using setItem() before getItem() as that will clear out the values. All you need in your head to alert the value of id is below:

var id = sessionStorage.getItem("id");
alert(id);

jsFiddle

(just re rerun the fiddle to see the result of the click)

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