【问题标题】:JQuery Set Odd, Even of TotaljQuery设置奇数,偶数的总数
【发布时间】:2014-06-08 00:37:06
【问题描述】:

我有一个汇总列和行的表格,并显示总和的结果。 我必须更改每个总数的颜色。如果是偶数,则将其设为“绿色”。如果它是奇怪的把它“红色”

这是我的桌子:

<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

【问题讨论】:

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


    【解决方案1】:

    试试这个,把这段代码放在 newSum() 函数中

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

    DEMO

    【讨论】:

    • 是的,它改变了输入文本的颜色,但我只想改变总和的颜色。
    • @devtreat 啊,我明白了,然后把 if 语句放在添加 sum 之前,就像这里的小提琴一样 jsfiddle.net/hdhZZ/5
    • 如果您不希望输入值改变颜色,请遵循jsfiddle.net/hdhZZ/8
    【解决方案2】:

    试试这个方法

    JQUERY 代码:

       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/

    快乐编码:)

    【讨论】:

      【解决方案3】:

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

      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.

      参考资料:

      【讨论】:

      • 很棒的代码大卫托马斯!我现在就去试试:)
      • 谢谢,希望对你有用! :)
      • 出于好奇,这对您的用例有用吗? (不是在寻找接受,特别是,只是想知道我的代码是否需要以任何方式改进。)
      【解决方案4】:

      我已更新您的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");
        }
      });
      

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-02
          相关资源
          最近更新 更多