Javascript:如何在DIV输出中添加数字?

时间:2017-01-30 19:55:07

标签: javascript jquery

我有一个指定总和的div:

$('#cost')

我想在此DIV输出中添加数字3。我的事情不起作用:

+$('#cost').text(parseInt(3));

1 个答案:

答案 0 :(得分:1)

您的代码用数字3覆盖文本。您需要获取原始值,解析它包含的字符串以获得数值等效,然后将其添加3。然后将数学结果设置为元素文本的新值。

var $price = $('#price');
var $quantity = $('#quantity');
var $total = $('total');

$('#price, #quantity').on("input", function() {

  // Do conversions first:
  price = parseFloat($price.val());
  quantity = parseFloat($quantity.val());
  
  // Always check user input before using it
  // (What if the user types non-numeric data or leaves a field blank?)
  if(!isNaN(price) && !isNaN(quantity)){
    
    // Then the math is straignt-forward:
    $('#total').text(price * quantity);
    
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="price">
<input type="text" id="quantity">
<span id="total"></span>