我有这个html表和跨度。我试图使它在每一行上value1和value2将加在一起并显示在同一行的sum单元格中。此外,第1行和第2行中value1,value2和Sum的每个值将相加并显示在该特定列的范围中。
我知道行很容易,但我可以在单个元素上为JavaScript事件侦听器提供多个函数,一个用于计算列,另一个用于计算行。或者我应该使用库(例如,knockoutJS)
import subprocess
subprocess.call(["ping", "-t"])
答案 0 :(得分:0)
https://jsfiddle.net/13e1kzm3/
<td>
<input style="width:50px" />
</td>
<td>
<input style="width:50px" />
</td>
<td>
<span id="sum">0</span>
</td>
function sumRows(){
$('tr').each(function() {
var sum = 0;
$(this).find('input').each(function() {
sum += +parseFloat($(this).val()) || 0;
});
$("#sum", this).text(sum);
});
}
function sumColumns(){
//...
}
$("table").bind("keyup", function() {
sumRows(this);
sumColumns(this);
});
$("table").bind("keydown, keyup", function() {...
答案 1 :(得分:0)
由于您已在问题上标记为Knockout
,因此以下是使用挖空功能更轻松地执行操作的示例
示例:https://jsfiddle.net/9aLvd3uw/188/
Html:
<body>
<table style="border: 1px solid">
<thead style="border: 1px solid">
<th>
Value 1
</th>
<th>
Value 2
</th>
<th>
Sum
</th>
</thead>
<tbody data-bind="foreach:TableItems">
<tr>
<td data-bind="text:$index()+1"></td>
<td >
<input style="width:50px" data-bind="textInput:Value1"/>
</td>
<td >
<input style="width:50px" data-bind="textInput:Value2"/>
</td>
<td >
<span id="r1Sum" data-bind="text:RowTotal"></span>
</td>
</tr>
</tbody>
</table>
<div>
<span>Number of row(s):</span><span data-bind="text:TableItems().length"></span>
</div>
<div>
<span>Value 1 column total:</span><span data-bind="text:Column1">0</span>
</div>
<div>
<span> Value 2 column total: </span><span data-bind="text:Column2">0</span>
</div>
<div>
<span>Sum column total:</span><span data-bind="text:Column3"></span>
</div>
<input type="button" value="Add New Row" data-bind="click:AddRow"/>
VM:
var TableItemViewModel = function (data){
var self = this;
self.Value1 = ko.observable(data.value1);
self.Value2 = ko.observable(data.value2);
self.RowTotal = ko.computed(function () {
return parseInt(self.Value1()? self.Value1() : 0) + parseInt(self.Value2()?self.Value2() :0);
});
}
function MainViewModel() {
//Sample data
var obj = [{value1 : 1 , value2 :11 },{value1 : 2 , value2 :22 }];
var self = this;
self.TableItems = ko.observableArray([]);
self.TableItems($.map(obj, function (item) {
return new TableItemViewModel(item);
}));
self.Column1 = ko.computed(function () {
var sum = 0 ;
ko.utils.arrayForEach(self.TableItems(), function (item) {
sum = sum + parseInt(item.Value1()) ;
});
return sum;
});
self.Column2 = ko.computed(function () {
var sum = 0 ;
ko.utils.arrayForEach(self.TableItems(), function (item) {
sum = sum + parseInt(item.Value2()) ;
});
return sum;
});
self.Column3 = ko.computed(function () {
var sum = 0 ;
ko.utils.arrayForEach(self.TableItems(), function (item) {
sum = sum + parseInt(item.RowTotal()) ;
});
return sum;
});
self.AddRow = function (){
self.TableItems.push(new TableItemViewModel({value1 : 1 , value2 :1 }))
}
}
ko.applyBindings( new MainViewModel);