JQuery Set Odd,甚至是Total

时间:2014-04-23 09:16:30

标签: javascript jquery colors html-table jquery-selectors

我有一个对Columns和Rows求和的表,并显示总和的结果。 我必须改变每个总数的颜色。如果是偶数,则将其设为“绿色”。如果是奇数则将其设为“红色”

这是我的表:

<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());
    });
}

DEMO JSFIDDLE

5 个答案:

答案 0 :(得分:2)

试试这个,将下面的代码放在newSum()函数

 if ((this.value % 2 == 0)) {
     $(this).css('color', 'green');
 } else {
     $(this).css('color', 'red');
 }

DEMO

答案 1 :(得分:2)

试试这种方式

JQUERY CODE:

   if (total % 2 == 0)
      $table.find('.totalCol td:nth-child(' + thisNumber + ')').css('color', 'green'); //set green to even total
   else 
      $table.find('.totalCol td:nth-child(' + thisNumber + ')').css('color', 'red'); //set red to odd total

现场演示: http://jsfiddle.net/hdhZZ/7/

快乐编码:)

答案 2 :(得分:2)

我意识到您已经接受了答案,但我建议您重写以下方法(尽管着色方法与其他答案所建议的相同):

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);

JS Fiddle demo

参考文献:

答案 3 :(得分:1)

我已更新了您的fiddle,请检查。

$(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");
  }
});

答案 4 :(得分:1)

每次更改其中一个输入时,请检查总值是奇数还是偶数... 这很粗糙,我会切换一个类而不是编辑内联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');
        }
    });
});