简体   繁体   中英

Finding a cell with a specific value and applying a class to a cell in the same row

I have a ranking table with specific Elo ratings for each player. Depending on their Elo rating I want the player's name to be a specific color based on their rank. I have been using the code below:

if (parseInt($("td.data-rating").val()) > 100) {
  $(this).closest("tr").find("td.data-name").addClass("important");
}

JSFiddle why does this code not work? Am I using "this" incorrectly?

You have several issues:

  • The this keyword refers to the Window object
  • Only HTMLInputElement have values, the use of .val() is incorrect
  • You must iterator over each of the <td> elements to set the classList

This should work for you:

 $(function() { $("td.data-rating").each((i, el) => { if (parseInt(el.textContent) > 1000) { $(el).closest("tr").find("td.data-name").addClass("important"); } }) }) 
 .important { color: red; } 
 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <table> <tr> <td class="data-name">Player 1</td> <td>1</td> <td class="data-rating">1200</td> </tr> <tr> <td class="data-name">Player 2</td> <td>1</td> <td class="data-rating">1150</td> </tr> <tr> <td class="data-name">Player 3</td> <td>1</td> <td class="data-rating">1000</td> </tr> </table> </html> 

$("td.data-rating") will return array so .val will not work for it. you should use each function for that. Try below one.

$("td.data-rating").each(function (index) {
if(parseInt($(this).text()) > 1100) {
$(this).siblings().eq(0).addClass("important");
}
});

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