Javascript JQuery集合总数的奇数、偶数

Javascript JQuery集合总数的奇数、偶数,javascript,jquery,colors,html-table,jquery-selectors,Javascript,Jquery,Colors,Html Table,Jquery Selectors,我有一个表,可以对列和行进行求和,并显示求和的结果。 我必须改变每个总数的颜色。如果是偶数,就把它变成绿色。如果是奇数,就把它涂成红色 这是我的桌子: <table id="sum_table"> <tr> <td><input value="0" class="sum1" /></td> <td><input value="0" class="sum2"/></td

我有一个表,可以对列和行进行求和,并显示求和的结果。 我必须改变每个总数的颜色。如果是偶数,就把它变成绿色。如果是奇数,就把它涂成红色

这是我的桌子:

<table id="sum_table">
    <tr>
        <td><input value="0" class="sum1" /></td>
        <td><input value="0" class="sum2"/></td>
        <td><input value="0" class="sum3"/></td>
        <td class="total">0</td>
    </tr>
    <tr>
        <td><input value="0" class="sum1"/></td>
        <td><input value="0" class="sum2"/></td>
        <td><input value="0" class="sum3"/></td>
        <td class="total">0</td>
    </tr>
    <tr>
        <td><input value="0" class="sum1"/></td>
        <td><input value="0" class="sum2"/></td>
        <td><input value="0" class="sum3"/></td>
        <td class="total">0</td>
    </tr>

    <tr class ="totalCol">
        <td>0</td>
        <td>0</td>
        <td>0</td>
    </tr>

</table>
<button id="tabla">+</button>
JQuery:

//Sumamos las columnas
    $(document).on('keyup change','#sum_table tr:not(.totalCol) input:text',function() {
    var $table = $(this).closest('table');
    var total = 0;
    var thisNumber = $(this).attr('class').match(/(\d+)/)[1];

    $table.find('tr:not(.totalCol) .sum'+thisNumber).each(function() {
        total += parseInt(this.value);
    });

    $table.find('.totalCol td:nth-child('+thisNumber+')').html(total);
});


    //Añadimos filas y coumnas cuando se clica al boton "+".
    $("#tabla").click(function () {
        $("#sum_table tr:last-child").before("<tr>"+$("#sum_table tr:eq(0)").html()+"</tr>");
      $("tr:not(:last-child)").each(function () {
          var classname = $(this).find("td:last-child").index() + 1;
          $(this).find("td:last-child").before('<td><input class="sum' + classname + '" type="text" value="0"></td>');
      });
        $("#sum_table tr:last-child").append("<td>0</td>");
    });

//Creamos la funcion newSum para hacer la suma y mostrarlo en el total.
$(document).on('keyup','input',newSum);
function newSum() {
    var sum = 0;
    var thisRow = $(this).closest('tr');
    var total = 0;

    $(thisRow).find("td:not(.total) input").each(function () {
        sum += parseInt(this.value);
    });
    $(thisRow).find(".total").html(sum);
    $('.total').each(function () {
        total += parseInt($(this).html());
    });
}

试试这个,把下面的代码放到newSum函数中

 if ((this.value % 2 == 0)) {
     $(this).css('color', 'green');
 } else {
     $(this).css('color', 'red');
 }
我已经更新了你的密码,请查收

$(document).on('keyup change','#sum_table tr:not(.totalCol) input:text',function() {
  var $table = $(this).closest('table');
  var total = 0;
  var thisNumber = $(this).attr('class').match(/(\d+)/)[1];

  $table.find('tr:not(.totalCol) .sum'+thisNumber).each(function() {
    total += parseInt(this.value);
  });
  var total_field = $table.find('.totalCol td:nth-child('+thisNumber+')'); 
  total_field.html(total);
  if(total % 2 == true) {
    total_field.css("background","red");
  } 
  else {
     total_field.css("background","green");
  }
});
这样试试

JQUERY代码:

现场演示:


快乐编码:

每次更改一个输入时,检查总值是奇数还是偶数。。。 这很粗糙,我会切换一个类,而不是编辑内联css

$('td input').on('change', function(){
    $('.totalCol td').each(function(){        
        var $total = parseInt($(this).html());
        if ($total !==0 && $total % 2 === 0) {
            $(this).css('background-color','green');
        }
        else {
            $(this).css('background-color','#fff');
        }
    });
});

我知道你已经接受了一个答案,但我建议将你的方法改写为以下内容,尽管着色方法与其他答案所建议的相同:

function sumTotals(){
    // caching variables:
    var table = $('#sum_table'),
        inputRows = table.find('tr:not(.totalCol)'),
        inputCells = inputRows.find('td:not(.total)');

    // iterating over each of the 'td' elements in the '.totalCol' row:
    $('.totalCol td').each(function(i,e){

        /* i is the index of the current element over which we're iterating
           among the collection returned by the selector,
           e is the element (the 'this'), which we're not using here.

           We're using ':nth-child()' to look at the 'input' elements from
           each column, and creating an array of the values using 'map()'
           and 'get()': */
        var sum = inputRows.find('td:nth-child(' + (i + 1) + ') input').map(function(){
            return parseFloat(this.value) || 0;
        }).get().reduce(function (prev, curr) {
        /* 'reduce()' allows us to perform a calculation (summation) of the 
            values in the returned array: */
            return prev + curr;
        });

        // setting the text of the current 'td' to the sum,
        // using CSS to set the color to either green (even) or red (odd):
        $(this).text(sum).css('color', sum % 2 === 0 ? 'green' : 'red');
    });

    /* iterating over each of the rows with inputs, finding the
       last 'td', and updating its text: */
    inputRows.find('td:last-child').text(function(){
        // caching:
        var $this = $(this),
            /* getting all the previous 'td' elements, and their 'input'
               descendant elements, mapping their values: */
            sum = $this.prevAll('td').find('input').map(function(){
            return parseFloat(this.value) || 0;
        }).get().reduce(function (prev, curr) {
            return prev + curr;
        });

        // setting the color (as above):
        $this.css('color', sum % 2 === 0 ? 'green' : 'red');
        return sum;
    });
}

$('#sum_table').on('keyup change input paste', 'tr:not(.totalCol) input', sumTotals);

参考资料:

CSS: . . JavaScript: . . jQuery: . . . . . . .
是的,它改变了输入文本的颜色,但我只想改变总和的颜色。@devtreat啊,我明白了,然后在像小提琴一样添加总和之前放上if语句,如果你根本不想让输入值改变颜色,请遵循这段很棒的代码David Thomas!我现在就去试试:谢谢你,希望对你有用出于好奇,这对您的用例有用吗?不是寻找一个接受,特别是,只是想知道我的代码是否需要以任何方式进行改进。
function sumTotals(){
    // caching variables:
    var table = $('#sum_table'),
        inputRows = table.find('tr:not(.totalCol)'),
        inputCells = inputRows.find('td:not(.total)');

    // iterating over each of the 'td' elements in the '.totalCol' row:
    $('.totalCol td').each(function(i,e){

        /* i is the index of the current element over which we're iterating
           among the collection returned by the selector,
           e is the element (the 'this'), which we're not using here.

           We're using ':nth-child()' to look at the 'input' elements from
           each column, and creating an array of the values using 'map()'
           and 'get()': */
        var sum = inputRows.find('td:nth-child(' + (i + 1) + ') input').map(function(){
            return parseFloat(this.value) || 0;
        }).get().reduce(function (prev, curr) {
        /* 'reduce()' allows us to perform a calculation (summation) of the 
            values in the returned array: */
            return prev + curr;
        });

        // setting the text of the current 'td' to the sum,
        // using CSS to set the color to either green (even) or red (odd):
        $(this).text(sum).css('color', sum % 2 === 0 ? 'green' : 'red');
    });

    /* iterating over each of the rows with inputs, finding the
       last 'td', and updating its text: */
    inputRows.find('td:last-child').text(function(){
        // caching:
        var $this = $(this),
            /* getting all the previous 'td' elements, and their 'input'
               descendant elements, mapping their values: */
            sum = $this.prevAll('td').find('input').map(function(){
            return parseFloat(this.value) || 0;
        }).get().reduce(function (prev, curr) {
            return prev + curr;
        });

        // setting the color (as above):
        $this.css('color', sum % 2 === 0 ? 'green' : 'red');
        return sum;
    });
}

$('#sum_table').on('keyup change input paste', 'tr:not(.totalCol) input', sumTotals);