开发者

Transforming tablecell content with CSS or jQuery

I have a html table similar to this:

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

The cells in the first column contain a numeric value of 1, 2 or 3.

I’m looking for a neat way of transforming this value into something more “graphical” using a client side approach such as CSS (preferably) or jQuery. For example, instead of “1” the cell content should be rendered as an icon, or a dot with a red color. Just setting the background color would also be ok.

UPDATE:

Thanks for all the suggestions. It seems it was just the Each method from jQuery I was missing. :)

Here's my final code. I wrapped it in separate function which is called on document ready and after table updates.

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


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

Thanks Eikern for the tip.


For jQuery, try

$("tr td:first").each(function(){
   // do transformations like $(this).html(...)
});


Yet another solution:

$("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. */


If you know it's going to be numeric, you could do something like:


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

This gives you a result that looks like:

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

But of course, you could style it, change the counter character, use an image instead of °, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜