【发布时间】:2021-08-13 18:50:59
【问题描述】:
希望帮助为多个动态 div 设置多个 cookie。
我可以为 1 个 div 设置 1 个 cookie,但是,当我将超过 1 个项目/div 添加到购物车时,cookie 只会设置在第一个子/div 上。
添加到购物车的 div 数量始终是未知的并且是动态生成的...如何为每个添加的购物车项目创建唯一的 cookie?
非常感谢您的时间和帮助!任何帮助将不胜感激, 史蒂夫。
此处提供代码
$('#bag_active').on('click', '.add-to-cart', function setCookie() {
alert("COOKIES SET");
var customObject = {};
customObject.name = document.getElementById("cart_product_name").value;
customObject.price = document.getElementById("cart_product_price").value;
var jsonString = JSON.stringify(customObject);
document.cookie = "cookieObject=" + jsonString;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="bag_active" class="product-card">
<h1 class="title">Cookie Title 1</h1>
<h2 class="subtitle">Cookie Price 1</h2>
<button id="1" type="button" class="btn add-to-cart" aria-pressed="true" onclick="setCookie()">Add to Bag</button>
<input type="hidden" id="cart_product_name" name="Cookie Name 1" value="Cookie Name 1">
<input type="hidden" id="cart_product_price" name="Cookie Price 1" value="Cookie Price 1">
</div>
<div id="bag_active" class="product-card">
<h1 class="title">Cookie Title 2</h1>
<h2 class="subtitle">Cookie Price 2</h2>
<button id="2" type="button" class="btn add-to-cart" aria-pressed="true" onclick="setCookie()">Add to Bag</button>
<input type="hidden" id="cart_product_name" name="Cookie Name 2" value="Cookie Name 2">
<input type="hidden" id="cart_product_price" name="Cookie Price 2" value="Cookie Price 2">
</div>
<div id="bag_active" class="product-card">
<h1 class="title">Cookie Title 3</h1>
<h2 class="subtitle">Cookie Price 3</h2>
<button id="3" type="button" class="btn add-to-cart" aria-pressed="true" onclick="setCookie()">Add to Bag</button>
<input type="hidden" id="cart_product_name" name="Cookie Name 3" value="Cookie Name 3">
<input type="hidden" id="cart_product_price" name="Cookie Price 3" value="Cookie Price 3">
</div>
【问题讨论】:
-
读取之前设置的cookie,解析,添加新信息,序列化并再次存储。
-
@aleksxor 非常感谢,讨厌成为那个人,哈哈,但你是怎么做到的?
标签: javascript cookies hidden-field dynamic-content custom-object