假设我有一个内容不确定的jQuery对象(来自可能是动态选择器或字符串的something ):
var $o = $(something);例如,现在如何计算jQuery对象本身中包含了多少个jQuery对象(即没有包含元素的后代)?我可以
var l = $o.filter( function () { return $(this).is("div"); } ).length;其他想法?
发布于 2010-09-17 18:19:26
.filter()使用一个选择器,所以
$o.filter('div')应该就足够了。
当然,您可以为此创建一个插件:
$.fn.count = function(selector) {
return this.filter(selector).length;
}; 发布于 2010-09-17 18:30:30
在jQuery对象中有两种计算特定类型元素的方法。使用哪种方法取决于in的定义。
$(this, that)的上下文来查找其中的内容。它是用.find()实现的如果要在对象中搜索后代,请使用.find()或上下文:
$o.find("div").length或
$("div", $o).length例如
<li>
<div></div>
<div></div>
</li>关于上述各点:
$("li").find("div").length // This is 2
$("div", "li").length // This is 2
$("li").filter("div").length // This is 0如果希望通过规则减少选定项的数量,请使用.filter()
<div class="a"></div>
<div></div>对于上述情况
$("div").filter(".a").length // This is 1
$("div").find(".a").length // This is 0
$(".a", "div").length // This is 0jsFiddle显示.find()和.filter()都在工作。
https://stackoverflow.com/questions/3737834
复制相似问题