开发者

detect the widest cell w/ jQuery

I have a table with different values. First co开发者_如何学Golumn contains labels. I need to get the width of the widest label. I assume I need some sort of a loop, but then what?

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

Thanks.


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


I assume that you have one <label> element inside all <td> elements in the first column (since it makes no sense to compare the widths of the <td> elements themselves — within the same column they are equally wide (not considering colspan != 1)):

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


Try this:

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

Note I tracked the actual width separately from the widest element. An alternate solution without this method would be to initialize widest to a dummy element with width = 0 and just compare $(this).width() with widest.width()

EDIT: Or, alternately, now that I realize you wanted only the width and not the actual element, you could use this version:

var widestWidth = 0;
$("#myTable td").each(function(t) {
     widestWidth = Math.max(widestWidth, $(this).width());
});


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


This should work - it will go through each of the tds (in myTable) and find the widest:

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

alternatively:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜