简体   繁体   English

如何排除包含具有特定类的TD的TR

[英]How to exclude the TR that contains the TD with a specific class

I have a function in which I take the first TR of my table and then I take all the TD of this TR. 我有一个函数,在该函数中,我获取表的第一个TR,然后获取该TR的所有TD。 Now I need to modify this function: when I take the first TR I need to check that if all the TD of my TR have the class 'HD1' I need to take the second TR of the table. 现在,我需要修改此功能:在获取第一个TR时,我需要检查我的TR的所有TD是否都具有“ HD1”类,因此我需要获取表的第二个TR。 I put my function below. 我把我的功能放在下面。 Thanks in advance. 提前致谢。

 function getColumnsIdx(id) {
   var header = $("table#" + id + " thead tr:eq(1)");
   var header_fields = $("td", header);
   var header_idx = new Object();
   header_fields.each(function(idx, val) {
     var $$ = $(val);
     var key = $$.text();
     header_idx[key] = idx;
   });
 return header_idx;
}

You can look for the first td without that class, and then take its parent: 您可以在没有该类的情况下查找第一个td ,然后采用其父级:

var header = $("table#" + id + " thead tr td:not(.HD1):eq(0)").parent();

This could, however, result in getting the third/fourth/etc row. 但是,这可能导致获得第三/第四/等行。 If you must always return the second row, even if those cells also all have the HD1 class: 如果必须始终返回第二行,即使这些单元格也都具有HD1类:

var header = $("table#" + id + " thead tr:eq(0)");
var header_fields = $("td", header);

if (header_fields.length && header_fields.length == header_fields.filter(".HD1").length) {
  header = header.next();
  header_fields = $("td", header);
}

Note: :eq() uses a zero-based index, so use eq(0) to select the first element. 注意:: :eq()使用从零开始的索引,因此请使用eq(0)选择第一个元素。

You can check if the first row contains only class="HD1" elements by comparing the length of that selector to the length of the <td> elements in general. 您可以通过将选择器的长度与<td>元素的长度进行比较来检查第一行是否仅包含class="HD1"元素。

If they're the same length (all of the <td> are HD1 ) - use the second row. 如果它们的长度相同(所有<td>均为HD1 )-使用第二行。 Otherwise, use the first. 否则,请使用第一个。

With HD1: 使用HD1:

 let $row = $("thead tr:first > .HD1").length === $("thead tr:first > td").length ? $("table tr").eq(1) : $("table tr").first(); $row.css("color", "red"); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td class="HD1">1</td> <td class="HD1">2</td> <td class="HD1">3</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> </table> 

Without HD1: 没有HD1:

 let $row = $("thead tr:first > .HD1").length === $("thead tr:first > td").length ? $("table tr").eq(1) : $("table tr").first(); $row.css("color", "red"); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> </table> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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