问题
I'm try to use jQuery to conditionally change the color of some table cells. I have a table:
<tr>
<td>Class Code</td>
<td class="qty">3</td>
<td>Science</td>
</tr>
<td>Class Code</td>
<td class="qty">4</td>
<td>Science</td>
</tr>
. . .
A style definition lowqty{color:red;}
I want to change the color of the second column when the number is below 4.
I'm attempting to do that with the following, but haven't got it to work.
$('.qty').change(
function() {
if ($(this).text() <= 3 ) {
$(this).addClass('lowqty');
}
});
I've tried 3 as a string as well as a number, and I've tried filter and add in addition to change.
回答1:
$('.qty').each(function() {
if (parseInt($(this).text()) < 4) {
$(this).addClass('lowqty');
}
});
That should do the trick. Also you're missing an opening TR tag:
http://jsfiddle.net/suDqH/
回答2:
Use .val() instead of .text() and that should work.
Also, you can't call a change event on a table cell - .change() is for select elements.
来源:https://stackoverflow.com/questions/15752923/conditional-change-of-text-colour-inside-table-cell