尝试使用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来做到这一点吗?谢谢!

+0

发布html以上 –

+0

更改sessionStorage到localStorage –

也许不是最好的解决方案,但如何将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,如果从第二个页面重定向。

+0

这不起作用 - 但我有一种感觉,我把代码放在错误的地方。我会在哪里放置这些行在第一页上? – bzd91

+0

我认为把这些行放在一个函数中是很好的,并且记得添加return语句。然后在任何你喜欢的地方调用它,但要确保你的url正确包含了src参数。 – YLS