开发者

jquery highlight row based on column value

Hi I am hoping that somebody can help me to tweak this JQuery code so that it will开发者_如何学Python highlight the entire data row rather than just the cell containing the value 'N'. I have tried to apply the code to the table row but it is still only highlighting the background color of the cell containing the value of 'N' where as I need to highlight the entire table row. Does anybody have any suggestions?

    <html>
    <head> 
    <script type="text/javascript" 
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script> 
    <script type="text/javascript">  

    $(document).ready(function(){
                       $('#table_id tr.y_n td').each(function(){
                                                           if ($(this).text() == 'N') {
                                                               $(this).css('background-color','#f00');
                                                               }
                                                               }); 
                       });

    </script>

    </head>
    <body>
    <table id="table_id">
      <tr><th>Question</th><th>Y/N?</th></tr>  
      <tr><td>I am me.</td><td>Y</td></tr>  
      <tr class="y_n"><td>N</td><td>Y</td></tr>  
      <tr><td>I am not sure.</td><td class="y_n">Y</td></tr>  
      <tr><td>This is a table.</td><td class="y_n">Y</td></tr>
     </table>  

     </body> 
     </html> 


You just need to add a closest call before your css call:

if ($(this).text() == 'N') {
    $(this).closest('tr').css('background-color','#f00');
}

Demo: http://jsfiddle.net/ambiguous/KSCyC/

The closest function goes through the DOM to find the nearest ancestor that matches the selector.

You could also use parent:

if ($(this).text() == 'N') {
    $(this).parent().css('background-color','#f00');
}

Demo: http://jsfiddle.net/ambiguous/RdGEy/


I believe parent() is what you want. Change the following line:

$(this).css('background-color','#f00');

to

$(this).parent().css('background-color','#f00')
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜