使用 jQuery 在本地存储上添加产品
Add products on local storage using jQuery
我有一个树枝视图,在其中显示产品目录,我希望当用户单击"添加"按钮时能够将每个产品保存在localStorage上。目前,我只能从一个页面中获取第一个产品。如果我更改页面并选择其他产品,则第一个产品将被替换。产品最终将进入购物车,然后使用控制器路径从那里进入实体。现在我想让这部分工作。
HTML+Twig代码:
<div id="parentDiv" class="product row">
{% for products in pagination %}
<div class="product col-sm-6 col-lg-6 col-md-6 hero-feature">
<div id="{{attribute(products ,'id')}}" class="product thumbnail">
<img id="prodImage" class="product img-responsive img-rounded" src="{{attribute(products ,'image')}}" style="width:150px;height:150px" >
<div class="caption">
<h4 id="prodPrice" class="product pull-right"><b>{{ attribute (products, 'price') }}Lei</b></h4>
<h4 id="prodName" class="product" style="height:100px;width:200px;">
<a id="prodLink" class="product"
href="{{ attribute (products, 'affiliatelink') }}"
target="_blank">{{attribute ( products, 'name') }}</br></a>
</h4>
</div>
<div class="add-to-cart" >
<button class="btn btn-danger" type="button">Adauga</button>
</div>
</div>
</div>
{% endfor %}
</div>
而jQuery代码:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {
$('button').on('click', function(){
var products =
{
prodID :$('.thumbnail').attr("id"),
prodName :$('#prodName').text(),
prodPrice :$('#prodPrice').text(),
prodImage :$('#prodImage').attr('src'),
prodLink :$('#prodLink').attr('href')
};
localStorage.setItem('products',
JSON.stringify(products));
var retrievedObject = JSON.parse(localStorage.getItem('products'));
console.log('retrievedObject: ', retrievedObject);
});
});
提前谢谢你。
您对存储("产品")使用相同的键。您可以使用不同的密钥并维护它。
假设您的产品 ID 是唯一的,然后使用它。
例如
localStorage.setItem('products-1,JSON.stringify(products));
localStorage.setItem('products-2,JSON.stringify(products));等等
参考以下代码
$(document).ready(function() {
var prodId = $('.thumbnail').attr("id");
$('button').on('click', function(){
var products =
{
prodID :$('.thumbnail').attr("id"),
prodName :$('#prodName').text(),
prodPrice :$('#prodPrice').text(),
prodImage :$('#prodImage').attr('src'),
prodLink :$('#prodLink').attr('href')
};
localStorage.setItem('products-' + prodId,
JSON.stringify(products));
var retrievedObject = JSON.parse(localStorage.getItem('products-' + prodId));
console.log('retrievedObject: ', retrievedObject);
});
});
相关文章:
- 在ListView中添加JSON数组中存储的图像-ReactNative
- 为本地存储添加高分
- 选择文本并添加到本地存储
- 将新对象添加到本地存储
- 如何将类似类型的多个对象添加到本地存储中
- 尝试将对象添加到存储阵列中,然后通过循环将它们写出
- 存储对追加动态添加的元素的引用
- 添加隐藏属性以存储其他属性值
- 如何在Javascript中向存储类添加自定义方法
- 如何将添加到列表框客户端的值存储到sessionScope
- 将本地存储密钥添加到下拉列表中
- 使用 jQuery 在本地存储上添加产品
- 检查本地存储中的记录是否在 1 分钟前添加
- 如何将动态添加的内容存储到数据库
- 如何在存储加载之前向面板添加遮罩,并在存储加载后删除
- 动态添加文本框并将其值存储在 mysql 中
- 将值添加到本地存储,而不是替换它
- 将对象添加到本地存储中的数组
- 将新对象添加到 chrome 本地存储
- 在 Extjs 网格(3)上添加存储数据