[英]Session storage items cart
I tried to adapt a code that I found on stackoverflow, but unfortunately I didn't succeed. 我试图改编我在stackoverflow上找到的代码,但不幸的是我没有成功。 I want to store a variable that after refresh the page, will remain unchanged, until the cookies are cleared.
我要存储一个变量,该变量在刷新页面后将保持不变,直到清除cookie。
In the code I`ll show you, after I pressed refresh, the variable is reset to 0. 在代码中,当我按下“刷新”后,变量将重置为0。
Why? 为什么? Thanks.
谢谢。
JS: JS:
<script>
var WishCounter = 0;
let localStorage = window.localStorage
$(document).ready(function(){
$(".accordion-heading").click(function(){
if($(".accordion-body").is(':visible')){ /* check the condition accordion-body is visible or not */
$(".accordion-body").slideUp(200); /*if content is visible then close accordion-body with specific time duration */
$(".plusminus").text('+') /* add plus sign */
}
else{
$(this).next(".accordion-body").slideDown(200); /*if content not visible then
show the accordion-body */
$(this).children(".plusminus").text('-'); /* add minus sign */
}
});
$(".add-to-cart2").click(function(){
WishCounter++;
localStorage.setItem('WishCounter', WishCounter);
$(".cart-wish").text(WishCounter);
localStorage.getItem('WishCounter');
});
});
</script>
HTML : HTML:
<a class="add-to-cart2" role="button" data-toggle="modal">
<img src="images/popit/wish.png" class="buttons-featured-wish" width="91" height="91" border="0" alt=""></a>
The WishCounter
is always 0 because it gets set on page load. WishCounter
始终为0,因为它是在页面加载时设置的。 This can be fixed be setting the value of WishCounter
with localStorage.getItem();
这可以通过使用
localStorage.getItem();
设置WishCounter
的值来WishCounter
localStorage.getItem();
if it has a value 如果有价值
Example: 例:
<script>
let localStorage = window.localStorage;
var WishCounter = localStorage.getItem('WishCounter') === null ? 0 : localStorage.getItem('WishCounter');
$(".cart-wish").text(WishCounter);
$(document).ready(function(){
$(".accordion-heading").click(function(){
if($(".accordion-body").is(':visible')){ /* check the condition accordion-body is visible or not */
$(".accordion-body").slideUp(200); /*if content is visible then close accordion-body with specific time duration */
$(".plusminus").text('+') /* add plus sign */
}
else{
$(this).next(".accordion-body").slideDown(200); /*if content not visible then
show the accordion-body */
$(this).children(".plusminus").text('-'); /* add minus sign */
}
});
$(".add-to-cart2").click(function(){
WishCounter++;
localStorage.setItem('WishCounter', WishCounter);
$(".cart-wish").text(WishCounter);
});
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.