2012-02-21 45 views
2

我有一個表格,它會自動在較小的屏幕上隱藏列。在某些列上,標題橫跨兩行,如下所示:選擇:與jQuery的可見表單元格不起作用?

<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(); 
     } 

:可見選擇工作在更大的屏幕尺寸確定。在較小的尺寸上,我自動隱藏一些加載的列,然後選擇器不再工作。

在上面的例子中.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); 

是否有另一種方法來選擇可見元素?

+0

它似乎是老版本jQuery中的一個錯誤:http://bugs.jquery.com/ticket/4512。你的jQUery版本是最新的嗎? – alexp 2012-03-06 17:06:42

回答

0

試試下面的代碼來代替:

$.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(); 
    } 
});​ 

注意滋滋聲最新版本沒有:visible。看到一個JSFiddle here

相關問題