我想要做的是从每个subBlock类,得到" a"和" b"输入数据,乘以它们。从每个subBlock类中获取数据,完全添加它们并在" showTotal"中显示它们。标识。
这是html
<div id="mainblock">
<form>
<div class="subBlock">
<input class="a" name="a[]" />
<input class="b" name="b[]" />
</div>
<div class="subBlock">
<input class="a" name="a[]" />
<input class="b" name="b[]" />
</div>
<div class="subBlock">
<input class="a" name="a[]" />
<input class="b" name="b[]" />
</div>
<div class="subBlock">
<input class="a" name="a[]" />
<input class="b" name="b[]" />
</div>
<div class="subBlock">
<input class="a" name="a[]" />
<input class="b" name="b[]" />
</div>
</form>
</div>
<div id="showTotal"></div>
这里是javascript / jquery代码:
$(document).on("change", ".subBlock input", function(){
var totalFinal;
var subTotal;
// that = $(this);
$('#mainblock').find('.subBlock').each(function() {
subTotal = $(this).find('.a').val() * $(this).find('.b').val();
totalFinal = totalFinal + subTotal;
});
$('#showTotal').html(totalFinal);
});
我知道我在每个人用$(这个)做错了什么,任何建议,我该如何解决它。我搜索并尝试了其他帖子中的几个代码,但每次都失败了。
答案 0 :(得分:1)
totalFinal
变量初始化为零。否则,默认值为undefined
,您的结果为NaN
。|| 0
设置subTotal
变量的值设置值为零。
$(document).on("input", ".subBlock input", function() {
var totalFinal = 0,
subTotal;
$('#mainblock').find('.subBlock').each(function() {
subTotal = $(this).find('.a').val() * $(this).find('.b').val() || 0;
totalFinal = totalFinal + subTotal;
});
$('#showTotal').html(totalFinal);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="mainblock">
<form>
<div class="subBlock">
<input class="a" name="a[]" />
<input class="b" name="b[]" />
</div>
<div class="subBlock">
<input class="a" name="a[]" />
<input class="b" name="b[]" />
</div>
<div class="subBlock">
<input class="a" name="a[]" />
<input class="b" name="b[]" />
</div>
<div class="subBlock">
<input class="a" name="a[]" />
<input class="b" name="b[]" />
</div>
<div class="subBlock">
<input class="a" name="a[]" />
<input class="b" name="b[]" />
</div>
</form>
</div>
<div id="showTotal"></div>
&#13;