我试图改编我在stackoverflow上找到的代码,但不幸的是我没有成功。我要存储一个变量,该变量在刷新页面后将保持不变,直到清除cookie。
在我将向您展示的代码中,按刷新后,变量将重置为0。
为什么?谢谢。
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:
<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>
答案 0 :(得分:0)
WishCounter
始终为0,因为它是在页面加载时设置的。可以通过将WishCounter
的值设置为localStorage.getItem();
来固定该值(如果有值)
示例:
<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>