关于javascript:是否可以测试选择框中有多少个选项? | 珊瑚贝

Is it possible to test how many options are in a select box?


我正在使用 jQuery 1.6.2.

我正在使用 ColdFusion 和 jQuery 动态填充选择框。

When the options are returned and stuffed inside the select box, I’d jQuery to figure out how many options there are and adjust the size attr as needed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 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 );

如何有效地获得返回的选项数量?

  • 你能停止在你所有的标题中写标签吗?
  • 什么是”最新最好的 jQuery”?此声明取决于某个时间点,但此问题帖子将持续 [可能] 年。准确告诉我们您使用的是哪个版本;它不会伤害!
  • jQuery的可能重复:我如何计算孩子的数量?
  • @Felix,我的问题更明确。另一个问题更具概念性。另外,那个人在他的问题中输入了”jQuery”,应该受到警告,就像我一样。 :>


是的,只需使用 length 属性…

1
var numOfOptions = $(‘#Select option’).length;
  • @Evik James,没问题。很高兴我能帮上忙。
  • 我会很乐意尽快这样做。我试过了,但我认为至少有十分钟。


只需选择选项并测试生成的 jQuery 对象的长度属性:

1
console.log($(“#Select option”).length);

你可以使用这个:

1
var NumOfOptions = $(“#AlbumsSelect option”).length;
  • 是的,这也很完美。谢谢!


尝试使用javascript的属性.length

1
var length = $(“option”).length;

来源:https://www.codenong.com/7501004/

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?