简体   繁体   中英

Use Javascript to change a table cell color if its value is less than another

Can't figure out what I'm doing wrong here:

Just want cell .tt to be red when its numerical values is less than cell dd

HTML:

<table class="colorMe">
    <tr><td class="tt">2000</td><td>3500</td></tr>
    <tr><td>3000</td><td>2500</td></tr>
    <tr><td id="dd">4000</td><td>4500</td></tr>
</table>

JS:

$(".colorMe .tt" ).each(function() {
    var val = parseInt(this.innerHTML, 10);
    if (val < document.getElementById("dd");) {
        this.style.backgroundColor = "#F00000";
    }
});

No idea why this isn't working.

You have to get both values as you did the first.

$('.colorMe .tt').each(function() {
    var val = parseInt( $(this).text(), 10),
        dd = parseInt( $('#dd').text(), 10);
    if (val < dd) {
        $(this).css('background-color', 'red');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM