2011-08-30 34 views
4

我有一個表具有不同的值。第一列包含標籤。我需要獲得最寬標籤的寬度。我假設我需要某種循環,但那又如何?檢測最寬的單元格w/jQuery

$("#myTable td:nth-child(1)").width(); 

謝謝。

+3

走過每個使用'的每個()',並且檢查每一個的寬度'()'。我不認爲有一個更簡單的方法 –

+1

表中的所有第一列td元素不會是相同的寬度?你在尋找td元素內部的寬度嗎? – jfriend00

+0

這裏有一個'.reduce()'函數,以及'.map()'在jQuery中會很有用。 – Orbling

回答

4
var w = 0; 
$("#myTable tr td:first").each(function(){ 
    if($(this).width() > w){ 
     w = $(this).width(); 
    } 
}); 
+0

這是所有列中最寬的一列,而不僅僅是問題的第一列。 – jfriend00

+0

@ jfriend00:已修復 –

0

這應該工作 - 它會經過每個TDS(在myTable的),並找到最廣:

var widest = 0; 
$("#myTable tr td:first").each(function() 
{ 
    widest = ($(this).width() > widest) : $(this).width() : widest; 
}); 

或者:

var widest = 0; 
$("#myTable tr td:first").each(function() 
{ 
    if($(this).width() > widest){ 
     widest = $(this).width() 
    } 
}); 
+2

這是所有專欄中最寬的專欄,不僅僅是問題提到的第一欄。 – jfriend00

+0

這應該修復它:) –

2

試試這個:

var widest; 
var widestWidth = 0; 
$("#myTable td").each(function(t) { 
    if($(this).width() > widestWidth){ 
     widest = $(this); 
     widestWidth = $(this).width(); 
    } 
}); 
//Now widest points to the widest element 

注意我跟蹤了實際寬度separatel來自最廣泛的元素。沒有這種方法的另一種解決方案是將最寬初始化爲寬度爲0的虛擬元素,並且僅以最寬的寬度比較$(this).width()。我知道你想要的只有寬度,而不是實際的元素,你可以使用這個版本:

var widestWidth = 0; 
$("#myTable td").each(function(t) { 
    widestWidth = Math.max(widestWidth, $(this).width()); 
}); 
2
var widestTdLabel=0; 
$('#myTable td').each(function(index) { 
    if($(this).find('label').width()>widestTdLabel) 
     widestTdLabel=$(this).find('label').width(); 
}); 
alert(' width of the widest label is:'+widestTdLabel); 
3

我假定你已經在第一列的所有<td>元素中一個<label>元素(因爲它沒有感覺比較它們的寬度<td>元素LVES同一列內—它們同樣寬(不考慮colspan != 1)):

var widestLabel = 0; 
$("#myTable td:nth-child(1) label").each(function() { 
    widestLabel = Math.max(widestLabel, $(this).width()); 
});