假设我有一个内容不确定的jQuery对象(something可能是动态选择器或HTML字符串):
var $o = $(something);
Run Code Online (Sandbox Code Playgroud)
现在,例如,我如何计算jQuery对象本身<div>包含多少个对象(即没有包含元素的后代)?我可以
var l = $o.filter( function () { return $(this).is("div"); } ).length;
Run Code Online (Sandbox Code Playgroud)
其他想法?
.filter() 拿一个选择器,所以
$o.filter('div')
Run Code Online (Sandbox Code Playgroud)
实际上应该足够了.
当然,您可以为此创建一个插件:
$.fn.count = function(selector) {
return this.filter(selector).length;
};
Run Code Online (Sandbox Code Playgroud)
有两种方法可以计算jQuery对象中某种类型的元素.您使用哪种方法取决于您的定义in.
.find().length - 查找由适合模式的jQuery对象表示的DOM元素的所有后代.也可以使用表单的上下文在其中$(this, that)找到它.它是使用实现的.find()
.filter().length - 减少jQuery对象表示的所选DOM元素集,使其仅包含与模式匹配的元素.
如果要在对象中搜索后代,请使用.find()或上下文:
$o.find("div").length
Run Code Online (Sandbox Code Playgroud)
要么
$("div", $o).length
Run Code Online (Sandbox Code Playgroud)
例如
<li>
<div></div>
<div></div>
</li>
Run Code Online (Sandbox Code Playgroud)
对于上述:
$("li").find("div").length // This is 2
$("div", "li").length // This is 2
$("li").filter("div").length // This is 0
Run Code Online (Sandbox Code Playgroud)
<div class="a"></div>
<div></div>
Run Code Online (Sandbox Code Playgroud)
对于上述
$("div").filter(".a").length // This is 1
$("div").find(".a").length // This is 0
$(".a", "div").length // This is 0
Run Code Online (Sandbox Code Playgroud)
jsFiddle显示.find()和.filter()工作.