我试图用each
JQuery函数对多个字段求和,但我总是返回'0'。 This topic was discussed here.我借用了代码段。
我的语法不正确,但无法确定它是什么。我一直返回null值或0。
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<table>
<tr>
<td>
Value 1
</td>
<td>
Value 2
</td>
<td>
Sum
</td>
</tr>
<tr>
<td>
<input class="SumText" type="text" id="Value1">
</td>
<td>
<input class="SumText" type="text" id="Value2">
</td>
<td>
<input class="TotalText" type="text" id="Total">
</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.SumText').change(function(){
var sum = 0;
// iterate through each td based on class and add the values
$('.SumText').each(function() {
var value = $(this).text();
alert("This.Text: " + $(this).text() + "Value: " + value);
// add only if the value is number
if(!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
$('#Total').val(sum);
});
});
</script>
答案 0 :(得分:1)
您在另一个问题中的代码是正确的(针对这种情况)。 <input>
个元素没有文字。他们有价值观:
$(this).val()