我有一个购物车图标,上面有另一个图标,用于计算购物车中有多少商品。这是代码
CSS:
.fa-stack[data-contador]:after{
position:absolute;
right:-10%;
top:-25%;
content: attr(data-contador);
font-size:70%;
padding:.6em;
border-radius:999px;
line-height:.75em;
color: white;
background:rgba(255,0,0,.85);
text-align:center;
min-width:2em;
font-weight:bold;
}
HTML
<span class="fa-stack fa-1x has-badge" data-contador="MY NUMBER">
<i class="fas fa-shopping-cart fa-2x"></i>
</span>
我正在使用 codeigniter 的购物车库并得到了这个:
<span class="fa-stack fa-1x has-badge" data-cantidad='<?= $this->cart->total_items(); ?>'>
<i class="fas fa-shopping-cart fa-2x"></i>
</span>
$this->cart->total_items(); returns the quantity of items
这有效,但只有当我刷新页面时,我的问题是如何在不刷新页面的情况下更新该值。谢谢
最佳答案
希望您仅将此用于 GUI 目的,因为客户端不可信。话虽这么说:
Controller :
function get_cart_items() {
echo json_encode(array('item_count' => $this->cart->total_items()));
exit();
}
JS:
//<span class="fa-stack fa-1x has-badge" id="cart-count" data-cantidad='<?= $this->cart->total_items(); ?>'>
$('.cart-add').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'path/to/get_cart_items',
dataType: 'json',
success: function (data) {
$('#cart-count').attr('data-cantidad', data.item_count);
}
});
});
注意:cart-add
是一个类,可以添加到任何触发新总计(或将商品添加到购物车)的按钮。 cart-count
是一个 id,要添加到具有 data-cantidad
属性的 span/div。
显然,您必须在任何需要它的页面上包含此 js,并预先加载 jquery。
关于php - 如何在不刷新页面的情况下更新 HTML data-* 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56159379/