2013-07-07 14 views
5

Załóżmy, że mam kilka elementów o innej treści tekstowej niż <span>.Zdobądź najszerszy element w zestawie jQuery

Jak mogę uzyskać najszerszy <span>?

jQuery jest w porządku. Dbam tylko o określenie rozpiętości, a nie o samą szerokość.

Podobnym pytaniem jest here. Ale otrzymują tylko wartość szerokości.

Oto jak zacznę:

$('span').each(function(id, value){ 
    if ($(this).width() > w) { 
    largestSpan = id; 
    } 
}); 

Odpowiedz

15
var maxWidth = 0; 
var widestSpan = null; 
var $element; 
$("span").each(function(){ 
    $element = $(this); 
    if($element.width() > maxWidth){ 
    maxWidth = $element.width(); 
    widestSpan = $element; 
    } 

}); 
+1

Minutę między prawie identycznych odpowiedzi. Wzniesiony tylko po to. –

+0

Ten jest bardziej elegancki i kompaktowy z dwóch. : O – DevlshOne

+1

Moja jedyna skarga dotyczy tego, że tworzysz nowy obiekt jQuery za każdym razem, gdy robisz '$ (this)'. Wydajność naprawdę ma znaczenie w pętli, więc lepiej ją zapisać raz. '$ element = $ (this)', a następnie odwołaj się '$ element' zamiast' $ (this) 'za każdym razem. –

5

jQuery zidentyfikować największą rozpiętość w div:

var oSpan;    // Container object for loop item 
var oWidest;   // Container object for current widest in loop 
var nWidth = 0;  // Int to store current span width 
var nWidest = 0;  // Int to contain widest items width 
var aWidest = [];  // Array to contain multiple matching spans 

// Call each function on spans within div 
$('#divContainer span').each(function(nIndex) 
{ 
    // Set reference to current span to avoid multiple calls per iteration 
    oSpan = $(this); 
    // Set current width to avoid multiple calls per iteration 
    nSpanWidth = oSpan.width(); 

    // Compare current width to widest width 
    if (nSpanWidth == nWidest) 
    { 
     // If exact,add to array and set current widest items 
     aWidest.push(oSpan); 
     oWidest = oSpan; 
     nWidest = nSpanWidth; 
    } 
    else if(nSpanWidth >= nWidest) 
    { 
     // If wider, reset array and set current widest item 
     oWidest = oSpan; 
     nWidest = nSpanWidth; 
     aWidest = [].push(oWidest) 
    } 
    else { } // Move along short stuff. 
}); 
Powiązane problemy