detect the widest cell w/ jQuery

前端 未结 5 900
挽巷
挽巷 2021-01-19 21:34

I have a table with different values. First column contains labels. I need to get the width of the widest label. I assume I need some sort of a loop, but then what?

相关标签:
5条回答
  • 2021-01-19 22:15
    var w = 0;
    $("#myTable tr td:first").each(function(){
        if($(this).width() > w){
            w = $(this).width();
        }
    });
    
    0 讨论(0)
  • 2021-01-19 22:24
    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);
    
    0 讨论(0)
  • 2021-01-19 22:27

    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());
    });
    
    0 讨论(0)
  • 2021-01-19 22:28

    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());
    });
    
    0 讨论(0)
  • 2021-01-19 22:32

    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 讨论(0)
提交回复
热议问题