我有两个文本输入文本框,我希望对用户输入的所有内容进行总计。下面是我的代码:
$(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
,我不知道为什么会这样。我在哪里出错,请引导我?
尝试这样。
$(document).ready(function(){
var total = 0;
$(".test").on("input", function(){
// Print entered value in a div box
if (parseInt($("#myInput1").val()) && parseInt($("#myInput2").val())) {
total = parseInt(parseInt($("#myInput1").val()) + parseInt($("#myInput2").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>
total =+ parseInt($(this).val());
首先,您必须等于该值,然后打印该数字。基本上,您完成了总和,然后打印了。
$(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>
使用更改事件代替输入事件。仅在“提交”值时才会触发,而不是每次击键都将触发。有关详细信息,请参见mdn。