是否可以测试选择框中有多少个选项?
问题描述:
我使用的是jQuery 1.6.2。是否可以测试选择框中有多少个选项?
我使用ColdFusion和jQuery动态填充选择框。
当选项被返回并填充到选择框中时,我想让jQuery找出有多少选项并根据需要调整大小attr。
// load the options into the select box
$("#Select").load("GlobalAdmin/ArtistUnassociatedAlbums.cfm?" + QString);
// test the number of options
var NumOfOptions = $();
var BoxSize = 0;
// do a calculation
if (NumOfOptions > 10) {
BoxSize = 10;
} else {
BoxSize = NumOfOptions ;
}
// adjust the select box size
$("#AlbumsSelect").attr("size", BoxSize);
如何有效获取返回选项的数量?
答
是啊,只是使用length
属性...
var numOfOptions = $('#Select option').length;
答
只要选择的选项,测试得到的jQuery对象的length属性:
console.log($("#Select option").length);
答
尝试使用JavaScript的性能。长度
var length = $("option").length;
答
您可以使用此:
var NumOfOptions = $("#AlbumsSelect option").length;
+0
是的,这也是完美的。谢谢! –
你能停止所有的标题写的标签吗? –
什么是“最新最好的jQuery”?这个陈述取决于某个时间点,但是这个问题帖子将持续[可能] _years_。告诉我们你正在使用哪个版本;它不会伤害! –
可能重复的[jQuery:我如何计算儿童数量?](http://*.com/questions/3546659/jquery-how-can-i-count-the-number-of-children) –