我有一个表格,每个单元格都有输入,除了一个 (.total) 指定每个表格行的总数。当其中一个输入发生变化时,我希望该行的总和发生变化。以下是我所能得到的。 HTML:
<table>
<tr>
<td><input value = "100"/></td>
<td><input value = "100"/></td>
<td><input value = "100"/></td>
<td class="total">300</td>
</tr>
<tr>
<td><input value = "200"/></td>
<td><input value = "200"/></td>
<td><input value = "200"/></td>
<td class="total">600</td>
</tr>
</table>
现在是 jQuery:
//add keyup handler
$(document).ready(function(){
$("input").each(function() {
$(this).keyup(function(){
newSum();
});
});
});
function newSum() {
var sum = 0;
var thisRow = $(this).closest('tr');
//iterate through each input and add to sum
$(thisRow).("td:not(.total) input:text").each(function() {
sum += this.value;
});
//change value of total
$(thisRow).(".total").html(sum);
}
任何帮助找出我做错了什么的人都将不胜感激。谢谢!
最佳答案
您的主要问题是在函数中使用了 this
。如果将该函数的主体直接放在 keyup
处理程序中,它应该可以工作。但是,在单独声明的函数体中的 this
本质上将引用它是其方法的对象。在上面的例子中,该对象将是 window
。
试试这个:
$(document).ready(function(){
$("input").each(function() {
var that = this; // fix a reference to the <input> element selected
$(this).keyup(function(){
newSum.call(that); // pass in a context for newsum():
// call() redefines what "this" means
// so newSum() sees 'this' as the <input> element
});
});
});
newSum()
中还有一些更表面的错误:
function newSum() {
var sum = 0;
var thisRow = $(this).closest('tr');
thisRow.find('td:not(.total) input:text').each( function(){
sum += parseFloat(this.value); // or parseInt(this.value,10) if appropriate
});
thisRow.find('td.total input:text').val(sum); // It is an <input>, right?
}
关于javascript - JQuery 求和特定表行中的所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5215185/