尝试使用sessionStorage更改图像的src
问题描述:
我有两个html页面,每个页面上都有一个图像。我需要能够点击第二页上的图像,并让它重定向到第一页 - 第一个图像变为第二个图像。尝试使用sessionStorage更改图像的src
什么是最佳/正确方式做到这一点?我一直试图通过在sessionStorage中存储src
来做到这一点,但它似乎没有工作。 这里是setItem
代码:
<script type="text/javascript">
$('.images').on('click', '.groupOne', function(){
var image = $(this).find("img"); // selects images inside group
var imageSrc = img.first().attr("src"); // get src of first image
sessionStorage.setItem("choice", imageSrc);
window.location.href = 'firstPage.html';
});
</script>
然后改变第一形象,我需要使用getItem
:
<script type="text/javascript">
$(document).ready(function() {
var imgTwo = sessionStorage.getItem("choice");
var imgOne = document.getElementById("pageOneImage");
imgOne.src = imgTwo; //sets src of img1 to src of img2
});
</script>
但这似乎并不奏效。有更简单的方法来使用更多的jQuery来做到这一点吗?谢谢!
答
也许不是最好的解决方案,但如何将src作为参数添加到查询字符串?
在第二页:
window.location.href = 'firstPage.html?src=' + src;
的第一页:
var reg = new RegExp("(^|&)src=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
var src = r != null ? unescape(r[2]) : null;
现在你得到了SRC,如果从第二个页面重定向。
发布html以上 –
更改sessionStorage到localStorage –