如何使用jquery获得下拉列表中所有元素的计数

How to get count of all elements which are in dropdown list using jquery

本文关键字:元素 jquery 何使用 下拉列表      更新时间:2023-09-26

我有一个下拉列表,像

 <select id="ddlProjects">
   <option value="315">resproject</option>
   <option value="320" style-"display:inline">newheavn</option>
   <option value="395" style="display:inline">cealon sales</option>
   <option value="395" style="display:inline">cealon sales</option>
 </select>

现在,我想计数的所有元素是"display:inline"的变化,我怎么能得到它。

在jquery中使用属性选择器获取下拉列表中选项的长度

    $('#ddlProjects').change(function(){
    var len = $(this).find('option[style="display:inline"]').length
    console.log(len)
   });

默认情况下,<option>display属性设置为inline

如果您仍然需要根据此属性进行过滤,请使用

$('#ddlProjects').change(function(){
    var count = $('option',this).filter(function(){
        var css =$(this).attr('style');
        return css !=undefined && css.indexOf('display:inline')>-1;
    }).length;
    console.log(count);
});

尝试在此上下文中使用.filter()

$('#ddlProjects').change(function(){
  var count = $(this).children().filter(function(){
    return $(this).css('display') === "inline" 
  }).length;
  console.log(count);
})

在这种情况下尝试使用attribute contains selector,因为option元素的默认显示属性是inline。

$('#ddlProjects').change(function(){
    var count = $('option[style*="display:inline"]',this).length;
    console.log(count);
});
演示

$('#ddlProjects option').filter(function() {
    return $(this).css('display') === 'inline';
}).length;