【问题标题】:addition of numbers in existing div box在现有 div 框中添加数字
【发布时间】:2013-05-03 20:07:56
【问题描述】:

如何将总和添加到页面上的现有数字?

最好只使用.empty(),然后通过jQuery 求和并在.html() 中再次设置?

例子

<div class="price">$200</div>

然后 jQuery 会将$50 添加到现有价格,新价格将是$250

根据无线电选择Yes 添加$50No 保持原样。

如果他们选择后退和第四次会发生什么,有什么方法可以撤消最后一次添加?

【问题讨论】:

  • $(.price).text( '$' + (parseInt($(.price).text(),10) + 50) );
  • 该解决方案完全没有必要。您将跟踪该值作为局部变量,然后在发生事件(即点击)时更新 div 的文本。

标签: jquery math add


【解决方案1】:

将价格存储在元素中:

<div class="product" data-price="50.0">I'm a product</div>

只要有变化就把它们加起来:

var total = 0;

$('.product').filter(function() {
    // Remove the ones that aren't checked or something
    return true;
}).each(function() {
    total += $(this).data('price');
});

$('.price').text('$' + total);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    相关资源
    最近更新 更多