【问题标题】:Selecting :visible table cell with jquery does not work?用 jquery 选择 :visible 表格单元格不起作用?
【发布时间】:2012-03-12 02:41:45
【问题描述】:

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

<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 选择器适用于较大的屏幕尺寸。在较小的尺寸上,我会在加载时自动隐藏一些列,然后选择器不再起作用。

在上面的例子中,.essential 类是可见的。然而,当我切换任何类时,以下总是返回 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 );

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

【问题讨论】:

标签: javascript jquery html-table jquery-selectors visibility


【解决方案1】:

试试下面的代码:

$.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 here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-10
    • 2010-10-20
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 2012-03-27
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多