javascript sessionStorage onclick 设置值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17884507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sessionStorage onclick set value
提问by Satch3000
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.
我有 4 个 div,根据用户单击的内容,我想为每个 div 设置一个变量,然后我想使用 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:
然后在<head></head>我添加的区域:
sessionStorage.setItem("id", "");
sessionStorage.getItem("id");
alert(id);
My problem is that the values are not changing and the onclickdoesn't see to be storing the new values.
我的问题是这些值没有改变,并且onclick看不到正在存储新值。
How can I do this right?
我怎样才能正确地做到这一点?
回答by Akhil Sekharan
Check this 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>
回答by Matias Elorriaga
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>
回答by Daniel Gimenez
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 idis below:
您设置值的 html 很好,但我不知道为什么使用setItem()之前使用,getItem()因为这会清除值。您需要在头脑中提醒价值的所有id内容如下:
var id = sessionStorage.getItem("id");
alert(id);
jsFiddle
js小提琴
(just re rerun the fiddle to see the result of the click)
(只需重新运行小提琴即可查看点击结果)

