无法使sessionStorage正常工作 [英] Can't get sessionStorage to work correctly
问题描述
我有多个按钮,单击它们会加载图像,并且即使页面刷新,图像也应该停留在该位置.当我使用此按钮时,即使单击其他按钮,也会始终显示具有最高setItem值的按钮.我该如何解决?
I have multiple buttons that when they are clicked an image is loaded and the image is supposed to stay there based even when the page refreshes. When I use this the button with the highest setItem value always shows even if I click on other button. How do I fix this?
这是脚本之一:
<script type="text/javascript">
var isImage1 = sessionStorage.getItem('2');
function showImage1() {
sessionStorage.setItem('isImage1', '2');
$("#loadingImage1").show();
$("#loadingImage").hide();
$("#loadingImage2").hide();
$("#loadingImage3").hide();
$("#loadingImage4").hide();
$("#loadingImage5").hide();
$("#loadingImage6").hide();
}
if(isImage1 == 2) showImage1();
</script>
这是我的按钮之一:
<input name="EPL/MECH DESIGN - TECHS" style="white-space:normal"
onclick="moveText(this.name);showImage1();form1.submit()"
style="width: 275px" type="button" value="7SBD EPL/Mech. Design Techs" />
更新:我已经更新了此行
Update: I have updated this line
var isImage1 = sessionStorage.getItem('2');
到
var isImage1 = sessionStorage.getItem('isIamge1');
但是我的问题仍然存在,即使我单击其他按钮,具有最大值的isImage仍然存在,因此仍然需要帮助.
but my issue still exists, that the isImage with the largest value stays even when i click the other buttons, so help is still needed.
推荐答案
在会话存储中,您将'isImage1'项目的值设置为'2'
In your session storage, you are setting the value of the 'isImage1' Item to '2'
sessionStorage.setItem('isImage1', '2');
但是在您要检索值的代码中,您实际上是在检索项目'2'
But in your code to retrieve the value you are actually retrieving the item '2'
var isImage1 = sessionStorage.getItem('2');
您需要将sessionStorage.getItem更改为引用'isImage1'
You need to change your sessionStorage.getItem to reference 'isImage1'
var isImage1 = sessionStorage.getItem('isImage1');
然后,您应该获得期望的价值.
Then you should get the value you are expecting.
在会话存储中有很多不错的jsfiddles.您可能会从中得到一些想法:
There are loads of good jsfiddles on session storage. you may get some ideas from this one:
http://jsfiddle.net/gabrieleromanato/XLRAH/
偶然地;这是您要存储的很小的值,为什么不将其存储在cookie中呢?
Incidently; this is a very small value you are storing, why not store it in a cookie instead?
基于您实际上具有多种功能的事实,最好采用Ken的解决方案,我唯一要添加的是关闭其他图像的通配符:
based on the fact that you have multiple functions exactly like this one, you are better off following Ken's solution, the only thing I would add is a wildcard to turn off the other images:
function showImage(imgNum) {
sessionStorage.setItem('Image',imgNum);
$("[id^=loadingImage]").hide();
$("#loadingImage" + imgNum).show();
}
showImage(sessionStorage.getItem('Image'));
按钮中的代码将是showImage(1)而不是showImage1();
The code in the buttons would then be showImage(1) instead of showImage1();
_Pez
这篇关于无法使sessionStorage正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!