javascript - 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>
解决方案
如果任何输入值是=""
,即什么都没有,总数将是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;
});
推荐阅读
- angular - 如何从订阅中返回价值?
- swift - 为什么这个闭包被调用了 1201 次而不是 900 次?
- c# - 无法在 Unity 中序列化和反序列化 JSON
- c# - 如何下载 Angular 6 中的 excel 文件
- r - 使用 splitTools 将折叠列附加到训练数据框
- python - 如何解决 AttributeError:“系列”对象没有属性“_mgr”
- vue.js - Nuxt.js 生成和 Three.js - SyntaxError: 不能在模块外使用 import 语句
- sql - 如何返回满足特定条件的行列表以及它之前的行?
- windows - 获取 git 中最后两个标签之间的提交列表 - 在 Windows 上 - 不知道标签
- javascript - 使JS生成的文档可以保存到磁盘