开发者

style table cells with data

I have a table with some data values. I would like to add styles to change the cells with values to hav开发者_JAVA百科e a background color and to add a border color to the first cell.

Can I do it with CSS only or do I need to ad some jQuery code? I'm fine with either or both.

Here's a demo of my table.


in jquery you could do (this adds a background color to all cell that have a value and adds a border to the first cell with a value but i can modify this as you want) EDIT - update to take account of the comment

$('table tr').each(function() {
    var firstDone = false;
    $(this).children('td').each(function() {
        if ($(this).text() != '') {
            if (!firstDone) {
                $(this).css('border', '2px solid yellow');
                firstDone = true;
            }
            $(this).css('background-color', 'green');
        }
    });
});

fiddle here http://jsfiddle.net/rkrHx/11/


It's usually better to add/remove CSS classes to the cells rather than style them directly with javascript. Try this one:

$("td").each(function(){
  if ($(this).text()) $(this).addClass('hasData');
});
$("tr").each(function(){
  $('td.hasData:first', this).addClass('firstCellwithData');
});

The second bit will only style the first cell with data, as I saw you clarify in the comments. Just add the styles to your CSS file for each of those two classes.

Demo: http://jsfiddle.net/rkrHx/19/

Just come up with some better class names than what I used ;)


Depending on the browsers you need to work, there is an :empty pseudoclass for css that you can use to style empty elements differently. According to this compatibility chart, the minimum version of IE which supports this is 9. However, it seems to be supported by all recent versions of all other browsers. You can use it like this.

td{
background-color: #F00;
}

td:empty {
background-color: #FFF;
}

The above will show all cells with data with a red (#F00) background, and all cells which are empty as having a white (#FFF) background.


You can set the border color through css but for setting background color based on data values you need to use javascript or jquery as below. You can use contains selector

$("table td:contains('datavalue')").css({backgroundColor:"yellow"});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜