代码之家  ›  专栏  ›  技术社区  ›  Jakob Gade

使用CSS或jQuery转换tablecell内容

  •  3
  • Jakob Gade  · 技术社区  · 15 年前

    我有一个类似以下内容的html表:

    <table>
      <tr>
        <td>1</td>
        <td>Some text...</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Some text...</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Some text...</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Some text...</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Some text...</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Some text...</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Some text...</td>
      </tr>
    </table>
    

    第一列中的单元格包含数值1、2或3。

    我正在寻找一种简洁的方法,使用客户端方法(如CSS(最好)或jQuery)将该值转换为更图形化的值。例如,单元格内容应呈现为图标或红色点,而不是1。只需设置背景色也可以。

    更新:

    这是我的最终代码。我将它包装在单独的函数中,该函数在文档就绪和表更新后调用。

    function fnTransformIcons() 
    { 
      var color;
    
      $("td.Icon").each(function() { 
      var value = $(this).html();
    
      switch (parseInt(value))
      { 
        case 0 : color = 'white'; break;
        case 1 : color = 'red'; break; 
        case 2 : color = 'green'; break; 
        case 3 : color = 'yellow'; break;
      } 
      $(this).css("backgroundColor", color); 
      });     
    }
    
    4 回复  |  直到 15 年前
        1
  •  3
  •   tanerkay    15 年前
    $(document).ready( function() {
        $("tr").each( function() {
            switch ($("td:first",this).text()) {
                case '1': color = 'red'; break;
                case '2': color = 'blue'; break;
                default: color = 'green';
            }
            $($("td:first",this).css("backgroundColor", color);
        });
    });
    

        2
  •  1
  •   Eli    15 年前

    对于jQuery,请尝试

    $("tr td:first").each(function(){
       // do transformations like $(this).html(...)
    });
    
        3
  •  1
  •   Darmen Amanbay Cherma Ramalho    15 年前

    $("tr td:first").each( function() {
        $(this).addClass('my_custom_class_'+$(this).text());
    });
    

    CSS:

    .my_custom_class_1 { background: red; }
    .my_custom_class_2 { background: green; }
    /* etc. */
    
        4
  •  1
  •   emmychan    15 年前

    如果您知道它将是数字的,您可以执行以下操作:

    
    $(function(){
       $('tr').each(function(){
        var cell = $(this).children().first(); //Get first td
        var new_contents = "";
        for (i=0; i <= parseInt(cell.text()); i++) {
          new_contents += '<span class="counter">&deg;</span>'; //or whatever counter character you like
        }
        cell.html(new_contents);
      });
    });
    
    

    °   Some text...
    °°  Some text...
    °°° Some text...
    °   Some text...
    °   Some text...
    °°  Some text...
    °°° Some text...
    

    但是当然,你可以设计它的样式,改变计数器字符,使用一个图像来代替字符等等。