jQuery change table cell text color based on text

I have a table which has columns of data that contain status. Two example statuses would be "Rejected" and "Paid"

What I'm wanting to do is changed the text color of the "Rejected" to red and the color of the "Paid" to green.

For the cells that have this status I added a classs to the td like:

<td class="status">
    @Html.DisplayFor(modelItem => item.Status)
</td>

So I can easily identify it.

I found I could change the color of all the statuses to Red using:

$('.status').css("color", "red");

Also I could get the value of the first one by:

alert($('.status').html());

However I'm unsure how to set a status color based on its text. ie for all "Received" set color to red and for all "Paid" set color to green.

Can somebody enlighten me on how to achieve this?

Am I even following the right approach using jQuery or is there a better css way?


This will work:

$('.status:contains("Paid")').css('color', 'red');
$('.status:contains("Received")').css('color', 'green');

http://jsfiddle.net/MMEhc/


Also I could get the value of the first one by...

With that selector you get a collection. And you do .html() on the first item in the collection.

You could loop through all status cells to check the status and change the color.

$('.status').each(function() {
  // check text and do styling
});

However this is not preferred (cause it is not needed). And it hurts performance.

You could also use jQuery .contains() for this ( http://api.jquery.com/contains-selector/ ).

Also not really needed. And I think not the best option performance wise.

So the best option (IMHO) is:

Why don't you just add two extra classes to the cells: status-received and status-paid since you already know the status of the cells while rendering them.

So you just could do:

$('.status-received').css("color", "red");
$('.status-paid').css("color", "red");

Or drop the jQuery entirely (since we don't need it any more (unless we are going to change the cells dynamically)) and just style the two classes uses CSS.


If you are printing the table from a database, simply assign a class to the td based on the result.

Then assign background color to that class.

td.paid {
 display:block;
background-color:red;

}

td.recieved {
 display:block;
background-color:green;
}

Why do you need to use javascript for this in the first place?

If I am not mistaken, the above code is jQuery so don't forget to add the Lib if you use that.

链接地址: http://www.djcxy.com/p/31024.html

上一篇: 根据真假来改变表格列的颜色

下一篇: jQuery基于文本更改表格单元格的文本颜色