我有两个文本输入文本框,我想计算用户未输入的所有内容的总和。下面是我的代码:
$(document).ready(function(){
var total = 0;
$(".test").on("input", function(){
// Print entered value in a div box
total += parseInt($(this).val());
$("#result").text( total);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput"></p>
<div id="result"></div>
当我先输入10
时,需要11
,然后如果我输入100,则需要111
,我不明白为什么会这样正在发生。我哪里出错了,请指导我?
最佳答案
在您的代码上,当您输入第一个数字时,由于您的代码total += parseInt($(this).val())
,它已被计算为总计。例如,如果您按第一个数字为 1,则此时总计将更新为 total = Total + 1
,等于 1,在第二次按键时,例如,取 0,则您的输入值将变为10. 计算当前总值为total = Total + 10
。这就是为什么你得到 11 作为答案
尝试这样。
$(document).ready(function(){
$(".test").on("input", function(){
let total = 0;
$('.test').each(function() {
if (!isNaN(parseInt($(this).val()))) {
total += parseInt($(this).val());
}
});
$("#result").text(total);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><input type="text" class="test" placeholder="Type something..." id="myInput1"></p>
<p><input type="text" class="test" placeholder="Type something..." id="myInput2"></p>
<div id="result"></div>
关于javascript - 如何在 jQuery 中检测文本输入框中的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58538736/