jquery 根据列值突出显示行

Bvi*_*let 3 html css jquery

您好,我希望有人可以帮助我调整这个 JQuery 代码,以便它突出显示整个数据行,而不仅仅是包含值“N”的单元格。我尝试将代码应用到表行,但它仍然只突出显示包含“N”值的单元格的背景颜色,因为我需要突出显示整个表行。有人有什么建议吗?

    <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> 
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 5

您只需要在调用之前添加一个closest调用css

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

演示: http: //jsfiddle.net/ambiguously/KSCyC/

closest函数遍历 DOM 来查找与选择器匹配的最近的祖先。

您还可以使用parent

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

演示: http: //jsfiddle.net/ambiguously/RdGEy/