获取change()函数</select>中的<select>项数

时间:2012-05-08 15:32:53

标签: jquery

我有以下js代码:

$("#mySelector").change(function(){
  console.log($(this).length);
});

我知道这是获取选择器中项目数的错误代码。但是我该如何以正确的方式得到这个数字?

P.S。 通常情况下,我应该使用$("#mySelector option").length来获取此数字。但是如何将option添加到$(this)运算符?

2 个答案:

答案 0 :(得分:1)

$("#mySelector").on('change', function(){
  console.log($('select', this).length);
});

还是选项?

$("#mySelector").on('change', function(){
  console.log($('option', this).length);
});

FIDDLE

答案 1 :(得分:0)

如果您尝试在选择下拉菜单中获取总<option>个标记,则可以执行此操作

options = 0;
$('{selector} option').each(function() {
    options++;
});
alert(options);​

或者精美vega建议的更好的方式

$('{selector} option').length