2011-12-14 26 views
1

我有一個選擇與選項,其轉換選擇不正常的選擇。如何找到使用jquery的選項的最大長度

<select> 
<option value="0">apple</option> 
<option value="1">orange</option> 
<option value="2">bannan fruit</option> 
</select> 

如何使用jquery查找選項(bannan水果)中的最大長度?

+0

@Simon是的字符串bannana水果這是選項中最大的文本... – Harry 2011-12-14 13:43:37

回答

6
var max_length = -1; 
$('option').each(function(){ 
    max_length = Math.max(max_length, $(this).text().length); 
}); 
alert(max_length); 
+2

只需將`.val()`更改爲`.text()`。 – jabclab 2011-12-14 13:48:34

+0

@jakeclarkson固定,謝謝! – Dogbert 2011-12-14 14:09:23

2

強制性一行代碼的解決方案:

Math.max.apply(null, $('option').map(function() { return $(this).html().length; }).toArray()) 

我想說Dogbert的解決方案可能是更具可讀性,但可能仍然會有一些有趣的教訓在這裏。這是怎麼回事:

  • 使用.map得到一個結果集只是用.toArray作出實際陣列出來的結果集,這將通過.apply
  • 數組傳遞到需要的長度
  • 的使用applyMath.max這將使第二個參數arguments集合,即寫Math.max(5, 6, 12);

的等效如果您使用Roatin Marth's excellent array extensions,代碼看起來有點整潔:

Array.prototype.max = function() { 
    return Math.max.apply(null, this) 
} 

$('option').map(function() { return $(this).html().length; }).toArray().max(); 
1

可以原型jQuery對象是這樣的:

jQuery.prototype.select_longest = function() { 
    var res = ""; 
    $(this).children().each(function() { 
     if ($(this).html().length > res.length) 
      res = $(this).html(); 
    }); 
    return res;  // use this line if you want biggest string 
    return res.length; // use this line if you want length of biggest string 
} 

然後你可以使用它像這樣:

var longest = $("#id").select_longest();