【问题标题】:How to update a HTML data-* attribute without refreshing page如何在不刷新页面的情况下更新 HTML data-* 属性
【发布时间】:2019-10-03 04:34:01
【问题描述】:

我有一个购物车图标,上面有另一个图标,用于计算购物车中有多少商品。这是代码

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();返回项目数量

这有效,但只有当我刷新页面时,我的问题是如何在不刷新页面的情况下更新该值。谢谢

【问题讨论】:

  • 您必须触发更新购物车的操作并使用 javascript 更新您的属性“data-cantidad”(如果您需要更新服务器端,可以使用 ajax 或 websocket)
  • 不需要服务器端更新,所以使用 AJAX 就可以了,但是我该怎么做呢?

标签: php jquery html css codeigniter


【解决方案1】:

希望您仅将其用于 GUI 目的,因为客户端不受信任。话虽这么说:

控制器:

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。

【讨论】:

  • 是的,它仅用于 GUI 用途并且完美运行!非常感谢:)
  • 我正在使用 Django,如何做到这一点?我按照本教程youtube.com/… 他制作了按钮,因此您需要重新加载页面以获取新值。如何更改它以提供新值,而无需重新加载页面?
猜你喜欢
  • 2011-06-15
  • 2022-11-27
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-29
  • 2017-05-11
  • 1970-01-01
相关资源
最近更新 更多