选择:使用jquery的可见表单元格不起作用

Selecting :visible table cell with jquery does not work?

本文关键字:表单 单元格 不起作用 使用 jquery 选择      更新时间:2023-09-26

我有一个表,它可以自动隐藏较小屏幕上的列。在某些列中,标题跨越两行,如下所示:

<table cellspacing="0">
  <thead>
    <tr>
      <th colspan="4" class="essential">Bestellung</th>
    </tr>
    <tr>
       <th>Nummer</th>
       <th>Datum</th>
       <th class="essential">Menge</th>
       <th class="essential">Wert</th>
   </tr>  
 </thead>
 ...

我有一些逻辑,这样用户就可以隐藏/显示他想要的列。我使用它来确保,如果第二个标题行中的所有列都被隐藏,那么第一个标题行的相应元素也会隐藏,当然反之亦然=一旦切换了第二个行元素,就会显示第一个行元素。

var doubles = thead.find( "tr:first-child th, TR:first-child TH" ).not('[rowspan=2]');
if ( thead.find("tr, TR").length > 1 && thead.find("tr:last-child th:visible, TR:last-child TH:visible" ).length === 0 ) {
    doubles.hide();
    } else {
       doubles.show();
       }

:visible选择器适用于较大的屏幕尺寸。在较小的大小上,我在加载时自动隐藏一些列,然后选择器就不再工作了。

在上面的例子中,.本质类是可见的。然而,当我切换任何一个类时,以下总是返回0:我不明白为什么控制台显示0,0,0,尽管1,2,3或所有4个元素都可见。

也许有人能告诉我可能的原因。

 console.log( thead.find("tr:last-child th:visible").length );
 console.log( thead.find("tr:last-child th").filter(":visible").length );
 console.log( thead.find("tr:last-child th[display=table-cell]").length );

有其他选择可见元素的方法吗?

请尝试以下代码:

$.expr[":"].displayed = function(e) { //Custom pseudo:
   return e && $(e).css("display") !== "none";
};
$(function() { //On DOMReady
    var thead = $("thead");
    doubles = thead.find("tr:first-child th, tr:first-child th").not("[rowspan=2]");
    if (thead.find("tr, TR").length > 1 && thead.find("tr:last-child th:displayed, tr:last-child th:displayed").length === 0) {
        doubles.hide();
    } else {
        doubles.show();
    }
});​

请注意,Sizzle的最新版本没有:visible。请在此处查看JSFiddle。