我有一个带选项的选项,它是一个转换后的选择而不是正常选项。
<select>
<option value="0">apple</option>
<option value="1">orange</option>
<option value="2">bannan fruit</option>
</select>
如何使用Jquery找到选项(bannan fruit)中的最大长度?
答案 0 :(得分:6)
var max_length = -1;
$('option').each(function(){
max_length = Math.max(max_length, $(this).text().length);
});
alert(max_length);
答案 1 :(得分:2)
强制性单行解决方案:
Math.max.apply(null, $('option').map(function() { return $(this).html().length; }).toArray())
我会说Dogbert的解决方案可能更具可读性,但这里可能还有一些有趣的课程。发生了什么:
.map
获取长度.toArray
从.apply
Math.max
将数组传递给apply
,这将使第二个参数成为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();
答案 2 :(得分: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();