【发布时间】:2015-10-20 20:28:28
【问题描述】:
我有一个带有多个元素的表单的 Page1。当我单击其中一个元素时,它会将我带到 Page2(在 Page2 中选择一个项目)并将该选定项目作为查询字符串传递回 Page1。然后我会将该项目附加到最后点击的元素中。到目前为止,它一直有效。
现在,问题是当我重复相同的事情时,即单击另一个元素,转到另一个页面,然后将该项目附加到 Page1,我无法获取这些元素上以前附加的项目。
所以,我想到了使用 localStorage 来保存 jquery 对象,然后使用该 localStorage 在每次刷新时检索那些选定的项目(在来自另一个页面之后)。
<form>
<div class="items" id="a">A</div>
<div class="items" id="b">B</div>
<div class="items" id="c">C</div>
</form>
//return querystring parameter
function GetURLParameter(sParam)
{
var fullQueryString = window.location.search.substring(1);
var sURLVariables = fullQueryString.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
$(function(){
arrImg = [];
var clickId = // function that returns the div element that is selected
var id = GetURLParameter('id');
if (id === 'item1') {
var img1 = $("<img id='item1' src='' />");
$('#' + clickId).append(img1);
var obj = $('#' + clickId).html();
arrImg.push(obj);
}
else if (id === 'item2') {
var img2 = $("<img id='item2' src='' />");
$('#' + clickId).append(img2);
var obj = $('#' + clickId).html();
arrImg.push(obj);
}
else if (id === 'item3') {
var img3 = $("<img id='item3' src='' />")
$('#' + clickId).append(img3);
var obj = $('#' + clickId).html();
arrImg.push(obj);
}
localStorage.setItem("ImgCookie", JSON.stringify(arrImg));
});
我得到 ImgCookie: "Item1" 只要。看不到其他 Item 对象被推送。
【问题讨论】:
标签: javascript jquery local-storage