Chr*_*son 49 javascript jquery
JQuery"has"方法有效地选择了具有特定后代的所有元素.
我想根据他们有特定祖先的事实来选择元素.我知道父母([选择器])和父母([选择器]),但这些选择父母而不是父母的孩子.
那么有一个祖先相当于"有"吗?
注意:我已经在层次结构的下面有一个元素的上下文,我将基于此选择,所以我不能进行"自上而下"查询.
更新
我显然在这里解释得非常糟糕,所以我会试着澄清一下:
<ul class="x">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul class="y">
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
我有一个jQuery对象,它已经包含2,3,4和5个元素.我想选择那些父类为class = x的元素.
希望更有意义.
Sam*_*son 71
对于干净的可重用解决方案,请考虑jQuery.fn
使用自定义方法扩展对象,该方法用于确定任何给定元素的特定祖先的存在:
// Extend jQuery.fn with our new method
jQuery.extend( jQuery.fn, {
// Name of our method & one argument (the parent selector)
within: function( pSelector ) {
// Returns a subset of items using jQuery.filter
return this.filter(function(){
// Return truthy/falsey based on presence in parent
return $(this).closest( pSelector ).length;
});
}
});
Run Code Online (Sandbox Code Playgroud)
这导致了一种新方法,$.fn.within
我们可以用它来过滤我们的结果:
$("li").within(".x").css("background", "red");
Run Code Online (Sandbox Code Playgroud)
这将选择文档上的所有列表项,然后仅过滤.x
为具有祖先的那些列表项.因为它在内部使用jQuery,你可以传入一个更复杂的选择器:
$("li").within(".x, .y").css("background", "red");
Run Code Online (Sandbox Code Playgroud)
这将收集过滤器,以从任何下降的项目.x
或.y
,或两者兼而有之.
小提琴:http://jsfiddle.net/jonathansampson/6GMN5/
psy*_*tik 42
if ( $('.foo').parents('.parentSelector').length ) { // has parent }
Dav*_*ing 36
如果我正确理解你的问题,这会做:
$.fn.hasAncestor = function(a) {
return this.filter(function() {
return !!$(this).closest(a).length;
});
};
$('.element').hasAncestor('.container').myAction();
<div class="container">
<span>
<strong class="element">strong</strong>
</span>
</div>
Run Code Online (Sandbox Code Playgroud)
$('body').hasParent('html') //true
$('div#myDiv').hasParent($('body')) //true
Run Code Online (Sandbox Code Playgroud)
// check if current element has parent element 'e'
$.fn.hasParent = function (e) {
return !!$(this).parents(e).length
}
Run Code Online (Sandbox Code Playgroud)