jQuery/JavaScript将一个按钮的值添加到总onClick中

jQuery/JavaScript adding value of a button to total onClick

本文关键字:添加 onClick 按钮 一个 JavaScript jQuery      更新时间:2023-09-26

我有一个按钮列表,其中包含数值和显示在页面顶部的总数。

单击其中一个按钮(例如"Add 100"),我希望将整数值100添加到显示的总分中。我希望总量能立即更新,而不是每次都要刷新页面。

我的想法对吗?这在JavaScript和jQuery中可能吗?或者我需要尝试其他方法吗?

使用jquery:

http://jsfiddle.net/mYuRK/

HTML

<button value="100">100</button>
<button value="200">200</button>
<button value="300">300</button>
<div class="total"></div>

JS

var theTotal = 0;
$('button').click(function(){
   theTotal = Number(theTotal) + Number($(this).val());
    $('.total').text("Total: "+theTotal);        
});
$('.total').text("Total: "+theTotal);   

类似这样的东西:

<div>Total : <span id="total">0</span></div>
<input class="add" data-amount="100" type="button" value="Add 100" />
<input class="add" data-amount="10" type="button" value="Add 10" />
<input class="add" data-amount="50" type="button" value="Add 50" />

jQuery

$(document).ready(function() {
  $('.add').click(function() {
     $('#total').text(parseInt($('#total').text()) + parseInt($(this).data('amount')));
  });
})

在这里工作演示,在这里工作.docs for.data(),在这里使用docs for.click()

下面是一段应该进行饮酒的示例代码。

<div id="total">0</div>
<input id="clickme" type="button" value="click me!" />
<script type="text/javascript">
    $(function() {
       $('#clickme').on('click', function() {
          var number = parseInt($('#total').text());
          number+=100;
          $('#total').text(number);
       });
    });
</script>

HTML:

<div>Total : <span id="total">0</span></div>
<button data-amount="10">Add 10</button>
<button data-amount="50">Add 50</button>
<button data-amount="100">Add 100</button>

JS:

$(document).ready(function() {
    $('button').bind('click', function() {
        var $this = $(this),
            $total = $("#total"),
            amount = $total.data("amount") || $total.text();
        amount += parseFloat($this.data('amount'));
        $total
            .data("amount", amount)
            .text(amount);
    });
});