首页 > 解决方案 > JQuery DOM 操作:即使使用 parseInt(),2 个数字的总和也会生成 NaN

问题描述

我的页面上有多个输入类型 =“数字”。每次用户单击“添加表单行”按钮时,它们都会动态生成。h2每次添加新输入时,我想根据每个输入的总和为我的 DOM中的元素赋值。但是,当我尝试对输入求和时,会返回 NaN。我怎样才能解决这个问题?

$(document).on('click', '.add-form-row', function(e){
        e.preventDefault();
        //cloneMore('.form-row:last', 'elements');
        // here starts the sum logic
        var tot = 0;
        currentTotal = $('.form-row').find('input[type=number]').each(function() {
            numberPrice = parseInt($(this).val())
            tot += numberPrice
        });
        $('.totalPrice').text(`<span>${tot}</span>`)
        return false;
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
   <input type="number" value="1">
   <input type="number" value="2">
   <button class="add-form-row">add</button>
   <div class="totalPrice"></div>
</div>

标签: javascriptjquery

解决方案


如果任何输入值是="",即什么都没有,总数将是NaN,因为parseInt("") = NaN,所以也许添加这样的条件可以解决您的问题:

$(document).on('click', '.add-form-row', function(e){
        e.preventDefault();
        //cloneMore('.form-row:last', 'elements');
        // here starts the sum logic
        var tot = 0;
        currentTotal = $('.form-row').find('input[type=number]').each(function() {
            if($(this).val() != ""){
                numberPrice = parseInt($(this).val());
                tot += numberPrice;
            }
        });
        $('.totalPrice').text(`<span>${tot}</span>`);
        return false;
    });

推荐阅读