如何使用jquery计算select中的选项数量

edg*_*dge 1 jquery

我想比较两个选择元素(HTML)中的项目数。我尝试使用 length 属性(使用 jquery),但它总是说两个选择元素的选项数 = 1。我正在动态填充两个选择元素。该怎么办?

      var $options=$("#test_select");
     $options.empty();
     $.each(t_test_list,function(index,value){
    $options.append($("<option>").text(value).attr("value",value));
     });

     var numdate=$("#date_select").length;
var numtest=$("#test_select").length;
alert(numdate);
alert(numtest);
if(numdate!=numtest)
    {
    alert("The number of dates do not match test cases!!!");
    }
Run Code Online (Sandbox Code Playgroud)

Awl*_*ton 6

尝试这个:

改变:

var numdate=$("#date_select").length;
var numtest=$("#test_select").length;
Run Code Online (Sandbox Code Playgroud)

到:

var numdate=$("#date_select").children('option').length;
var numtest=$("#test_select").children('option').length;
Run Code Online (Sandbox Code Playgroud)

您需要获取选项长度,它是 select 的子项而不是 select 长度。