如何计算jQuery对象中某个类型的所有元素?

假设我有一个内容不确定的jQuery对象(可能是动态选择器或HTML字符串):

 var $o = $(something); 

现在,例如,我如何计算jQuery对象本身包含多少

对象(即没有包含元素的后代)? 我可以

 var l = $o.filter( function () { return $(this).is("div"); } ).length; 

其他想法?

.filter()接受一个选择器,所以

 $o.filter('div') 

应该足够了。

当然,您可以为此创建一个插件:

 $.fn.count = function(selector) { return this.filter(selector).length; }; 

有两种方法可以计算jQuery对象中某种类型的元素。 您使用哪种方法取决于您对in的定义。

  1. .find() – 查找适合模式的jQuery对象表示的DOM元素的所有后代。 也可以使用$(this, that)forms的上下文来查找它。 它是使用.find()

  2. .filter() – 减少jQuery对象表示的所选DOM元素集,使其仅包含与模式匹配的元素。


如果要在对象中搜索后代,请使用.find()或上下文:

 $o.find("div").length 

要么

 $("div", $o).length 

例如

 
  • 对于上述:

     $("li").find("div").length // This is 2 $("div", "li").length // This is 2 $("li").filter("div").length // This is 0 

    如果要按规则减少所选项目的数量,请使用.filter()

     

    对于上述

     $("div").filter(".a").length // This is 1 $("div").find(".a").length // This is 0 $(".a", "div").length // This is 0 

    jsFiddle同时显示.find().filter()