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

时间:2012-03-06 17:20:16

标签: javascript jquery onclick add subtraction

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

点击其中一个按钮(例如“添加100”),我希望将整数值100添加到显示的总点数中。我想要总计立即更新,而不是每次都要刷新的页面。

我有正确的想法吗?这可能是使用JavaScript和jQuery还是我需要尝试别的东西?

4 个答案:

答案 0 :(得分:2)

使用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);   

答案 1 :(得分:1)

这样的事情:

<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')));
  });
})

Working demo heredocs for .data() here以及docs for .click() here

答案 2 :(得分:0)

这是一个应该做饮料的示例代码。

<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>

答案 3 :(得分:0)

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);
    });
});