简体   繁体   English

如果表格行,我将如何隐藏它<td>元素没有两个类之一?

[英]How would I hide a table row if its <td> elements don't have one of two classes?

I need to hide all of the rows in a particular table whose td elements do not contain one of two classes.我需要隐藏特定表中的所有行,其 td 元素不包含两个类之一。

If at least one of the td elements in a row contains one of these two classes, then don't hide it.如果一行中至少有一个 td 元素包含这两个类之一,则不要隐藏它。 Otherwise, hide the entire row.否则,隐藏整行。

class='class1'  
class='class2'  
id='mytable'

Any ideas?有任何想法吗?

Without an example it's difficult to know exactly what you are looking for, but perhaps something like this would work (air code):如果没有示例,很难确切地知道您在寻找什么,但也许这样的事情会起作用(空气代码):

$('#mytable tr').each(function() {
    var count = $('td.class1, td.class2', $(this)).length;
    if (!count) {
        $(this).hide();
    }
});

You can use this approach, perhaps it is not the shortest one, but hopefully clear to follow.您可以使用这种方法,也许它不是最短的方法,但希望可以清楚地遵循。 Lookup find, hasClass, eq methods in jQuery to learn more.在 jQuery 中查找 find、hasClass、eq 方法以了解更多信息。

var trs = $("table tr")

for( var i = 0; i < trs.length; i++) {
    var tds = $(trs.eq(i)).find("td");
  var trToKeep = true;
  for (var j = 0; j < tds.length; j++) {
    if (tds.eq(j).hasClass("x") || tds.eq(j).hasClass("y")){
        trToKeep = true;
      break;
    }
    else {
        trToKeep = false;
    }
  }
  if (trToKeep === false) {
  trs.eq(i).hide();
  } 
}

Working jsFiddle is here (classes you would look for are x or y):工作 jsFiddle 在这里(您要查找的类是 x 或 y):

https://jsfiddle.net/Turo/aj55q33w/ https://jsfiddle.net/Turo/aj55q33w/


Update: Updated my answer as you wanted to hide the ones that do not have the classes, not the ones that do.更新:更新了我的答案,因为您想隐藏没有课程的课程,而不是有课程的课程。

You can loop through the rows and check the class of each td .您可以遍历行并检查每个td的类。 I have loop through and used array and flag to decide whether to show or hide.我循环并使用数组和标志来决定是显示还是隐藏。 I also hide all at first then show them later with condition check.我也首先隐藏所有内容,然后通过条件检查显示它们。

var classNames = ['red', 'green'];
$(document).ready(function() {
  $('table tbody tr').each(function() {
    var show = false;
    $(this).hide();
    $('td', this).each(function() {
      var tdClass = $(this).attr('class');
      if ($.inArray(tdClass, classNames) != -1) {
        show = true;
      }
    });
    if (show) {
      $(this).show();
    }
  });
});

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

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