从父行减去
我试图减去父标题行的值(它们是各自子行的总和),但它只是在显示减号时继续添加。 我该如何减去?
的jsfiddle
HTML:
A
A1
A2
A3
B
B1
B2
B3
Total A - B
C
C1
C2
C3
D
D1
D2
D3
Total C - D
jQuery的:
$(function () { $('[class*="parent-"] input').attr('readonly', true); var total_par = $('tr.total'); $('input[type=text]').on('blur', function () { var totals = [0, 0, 0], parent_name = $(this).data('parent'), find_parent_row = $('tr.parent-' + parent_name); find_parent_row.nextUntil('[class*="parent-"]').find('input').each(function () { totals[$(this).parent('td').index() / 2 - 1] += +this.value; }); find_parent_row.find('input').each(function (i) { this.value = totals[i]; }); total_par.each(function () { totals = [0, 0, 0]; var par = $(this).data('par').split(','); $('[data-parent="' + par[0] + '"]').add('[data-parent="' + par[1] + '"]').each(function () { totals[$(this).parent('td').index() / 2 - 1] -= this.value; //subtract doesn't seem to be working! }); $(this).find('input').val(function (i) { return totals[i]; }); }); }); });
小提琴演示
HTML
JS
total_par.each(function () { totals = [0, 0, 0]; var par = $(this).data('par').split(','); // par[0] = A and par[1] = B $('[data-parent="' + par[0] + '"]').each(function () { //for A totals[$(this).parent('td').index() / 2 - 1] += +this.value; // add all values }); $('[data-parent="' + par[1] + '"]').each(function () {//for B totals[$(this).parent('td').index() / 2 - 1] += -1 * +this.value;// subtract all values --> number is multiplied with -1 to make it negative and than added }); $(this).find('input').val(function (i) { return totals[i]; //assign values to current input element inside class total }); });
要么
小提琴演示
total_par.each(function () { totals = [0, 0, 0]; var par = $(this).data('par').split(','); $('[data-parent="' + par[0] + '"]').each(function () { totals[$(this).parent('td').index() / 2 - 1] += +this.value; }); $('[data-parent="' + par[1] + '"]').each(function () { totals[$(this).parent('td').index() / 2 - 1] -= +this.value;// subtract all values }); $(this).find('input').val(function (i) { return totals[i]; }); });
小提琴演示
find_parent_row.nextUntil('[class*="parent-"]').find('input[data-parent="' + parent_name + '"]').each(function () { totals[$(this).parent('td').index() / 2 - 1] += +this.value; });
添加.find('input[data-parent="' + parent_name + '"]')