简体   繁体   English

使用localStorage在不同页面之间传递数据

[英]Using localStorage to pass data between different pages

I have a shopping basket where i want a user to be able to click on a button that takes them to a separate page whilst capturing their shopping basket contents (item names, quantities, prices, etc). 我有一个购物篮,我希望用户能够单击将他们带到单独页面的按钮,同时捕获他们的购物篮内容(商品名称,数量,价格等)。 At the moment i'm using localStorage to send just the item names to my new page however the only item that ever prints is the last item to be placed in a basket (i'm not sure how to stop localStorage overwriting data like it does). 目前,我正在使用localStorage将项目名称仅发送到我的新页面,但是唯一打印过的项目是放置在购物篮中的最后一个项目(我不确定如何停止localStorage像这样覆盖数据)。

This is the itemName section on the basket page. 这是购物篮页面上的itemName部分。

<!--START: itemnamelink--><a id="itemName" href="product.asp?itemid=[ITEM_CATALOGID]">[ITEM_NAME]</a><!--END: itemnamelink-->

This is a script i have on my basket page. 这是我在购物篮页面上拥有的脚本。

      jQuery( document ).ready(function($) {
    var itemName = document.getElementById('itemName');


       var arrayShop = [{name: itemName.textContent}];

if(localStorage.getItem("user") == null) { 
 localStorage.setItem("user",JSON.stringify([arrayShop]))
}
else{
  var newArray = JSON.parse(localStorage.getItem("user"));
  newArray.push(arrayShop);
  localStorage.setItem("user", JSON.stringify(newArray))
}


});

This is the script on a new page 这是新页面上的脚本

 jQuery( document ).ready(function($) {

var hst = document.getElementById("add");

console.log(localStorage.getItem("user"));

var items = JSON.parse(localStorage.getItem("user"));

   for (var i = 0; i < items.length; i++) {
 hst.innerHTML += "<tr><td>" + items[i].name + "</td><td>"+ items[i].price + 

"</td></tr>";
}





});

 <!--HTML ON THE PAGE -->


    <table id="add">
    <tr><td>Name</td><td>Price</td></tr>
</table>

I'm getting the following output which is the last item in the basket (there's 4 items in the basket). 我得到以下输出,它是购物篮中的最后一个项目(购物篮中有4个项目)。

Name    
110mm Chair 

I should be getting. 我应该得到。

Name
110mm Chair
Red Chair
Green Chair
Grey Chair

Below is my shopping cart 以下是我的购物车

 <div class="shoppingCartItems">
      <div class="titles2">
        <div class="item-info">[shoppingcart_items]</div>
        <div class="item-qty">[shoppingcart_quantity]</div>
        <div class="item-price">[shoppingcart_price]</div>
        <div class="item-total">[shoppingcart_total]</div>
        <div class="item-remove">&nbsp;</div>
        <div class="clear"></div>
      </div>
      <!--START: SHOPPING_CART_ITEM-->
      <div class="row">
        <div class="item-info">
          <div class="product-image"><!--START: itemthumbnail--><a href="product.asp?itemid=[ITEM_CATALOGID]"><img src="thumbnail.asp?file=[THUMBNAIL]" height="55" width="55" /></a><!--END: itemthumbnail--><!--START: thumbnailnolink--><img src="thumbnail.asp?file=[THUMBNAIL]" height="55" width="55" id="tnl" /><!--END: thumbnailnolink--></div>
          <div class="product-name-options"> 
            <!--START: itemnamelink--><a id="itemName" class ="itemName" href="product.asp?itemid=[ITEM_CATALOGID]">[ITEM_NAME]</a><!--END: itemnamelink--> 
            <!--START: itemnamenolink--><span id="spnItemName">[ITEM_NAME]</span><!--END: itemnamenolink--> 
            <!--START: itemoptions--> 
            <br />
            <a href='#' onclick="toggle('opt[ITEM_ID]')">View/Hide options</a><br />
            <div id=opt[ITEM_ID] name=opt[ITEM_ID] style="display:none;">[OPTIONS]</div>
            <!--END: itemoptions--> 
            <!--START: recurring_frequency-->
            <div class="recurring_frequency">This item will Autoship every <strong>[recurring_frequency]</strong></div>
            <!--END: recurring_frequency--> 
            <!--START: giftwraplink-->
            <div class="giftwraplink"> <a onclick="showGiftWrap('[ITEM_ID]')">[giftwrap_link]</a> </div>
            <!--END: giftwraplink--></div>
          <div class="clear"></div>
        </div>
        <div class="item-qty">
          <input type="text" name="qtyitemnum" value="[ITEM_QUANTITY]" size="3" maxlength="5" class="txtBoxStyle" />
          <input type="hidden" name="coliditemnum" value="[ITEM_ID]" size="3" maxlength="5" />
          <a href="#" onclick="document.forms['recalculate'].submit();return false;" class="update-qty">[shoppingcart_updatecart]</a>
        </div>
        <div class="item-price" id="itemPrice">[ITEM_PRICE] </div>
        <div class="item-total">[ITEM_SUBTOTAL]</div>
        <div class="item-remove"><a href="#" onclick="document.recalculate.qtyitemnum.value=0;document.recalculate.submit();"><i class="icon-cancel"></i></a></div>
        <div class="clear"></div>
      </div>
      <!--END: SHOPPING_CART_ITEM-->
      <div class="shoppingCartTotal">
        <div class="clear">&nbsp;</div>
        <div class="item-total">[CARTSUBTOTAL]</div>
        <div class="item-price">[shoppingcart_subtotal]</div>
        <div class="clear"></div>
        <!--START: DISCOUNTS-->
        <div class="clear">&nbsp;</div>
        <div class="item-total">[DISCOUNTS]</div>
        <div class="item-price">[checkout1_discounts]</div>
        <div class="clear"></div>
        <!--END: DISCOUNTS-->
        <div class="clear">&nbsp;</div>
        <div class="item-total"><strong>[CARTTOTAL]</strong></div>
        <div class="item-price"><strong>[shoppingcart_total]</strong></div>
        <div class="clear"></div>
      </div>
    </div>

I am not getting your shopping cart properly how you are doing it. 我的购物车操作不正确。 but using below code as the reference you can solve your problem. 但是使用下面的代码作为参考可以解决您的问题。

var uname = document.getElementById('uname1').value;

function checkFname(){
    var fname = document.forms["form"]["fname"].value;
    var chk_fname = fname.replace(/^[a-zA-z]{2,15}$/, '');
    if (fname != chk_fname) {
        document.getElementById("fname").className = '';
        return true;
    } 
    else if (fname == chk_fname) {
        document.getElementById("fname").className = 'error';
        return false;
    }
}


function Register(){
    var uname = document.getElementById('uname').value;
    var user = {
        'fname':document.getElementById('fname').value,
        };
    localStorage.setItem(uname,JSON.stringify(user));
}
function Validate(){
    Register();
}

While inserting the data in local storage Register() function will take the username as key and user can be an array which can contain data. 在本地存储中插入数据时, Register()函数将username作为键,并且user可以是可以包含数据的数组。

That it is because you are overwriting, not adding. 那是因为您正在覆盖,而不是添加。 In your code you need to append elements to your storage, using your last record and adding the new one, like this: 在代码中,您需要使用上一条记录并向其中添加新元素,从而将元素追加到存储中,如下所示:

var arrayShop = {name: 'Chair 2'};
if(localStorage.getItem("user") == null) { 
 localStorage.setItem("user",JSON.stringify([arrayShop]))
}
else{
  var newArray = JSON.parse(localStorage.getItem("user"));
  newArray.push(arrayShop);
  localStorage.setItem("user", JSON.stringify(newArray))
}

In this example my 'Chair 1' is your new element to add, soo if you execute it two times it will add a new element that is what passed in arrayShop. 在此示例中,我的“主席1”是要添加的新元素,因此,如果两次执行它,它将添加一个新元素,该元素是arrayShop中传递的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM