2013-07-07 3 views
5

たとえば、テキストの内容が異なる<span>要素の束があるとします。jQueryセットの中で最も広い要素を取得

どのようにして<span>を最大限に活用できますか?

jQueryは問題ありません。私は、幅自体の値ではなく、スパンの特定に気をつけます。

同様の質問はhereです。しかし、彼らは幅の値を得るだけです。ここで

は、私が開始したい方法は次のとおりです。divの中で最も広い範囲を特定するためのjQueryを使用した

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

答えて

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

}); 
+1

1分。それだけでアップアップ。 –

+0

これはよりエレガントでコンパクトな2枚です。 :O – DevlshOne

+1

私の唯一の不満は、 '$(this)'を実行するたびに新しいjQueryオブジェクトを作成していることです。効率は本当にループの中で重要なので、一度格納する方が良いでしょう。 '$ element = $(this)'を呼び出し、毎回 '$(this) 'ではなく' $ element'を参照してください。 –

5

:ほぼ同じ答えの間

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. 
}); 
関連する問題