jQuery"hasParent"

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 }

  • +1我最喜欢这个解决方案.但是jQuery确实应该将`hasParent()`添加到他们的API中. (2认同)

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)

  • 因为这个值过滤父母,而不是返回true/false,我建议将它重命名为`withAncestor`或`filterAncestor`.如果我正在阅读代码,我希望`hasAncestor`返回一个布尔值 (4认同)
  • 另一方面,`hasClass()`返回一个布尔值...让我想起[计算机科学中的两个难点]之一(http://martinfowler.com/bliki/TwoHardThings.html)...... (3认同)

Abd*_*UMI 8

$('body').hasParent('html') //true

$('div#myDiv').hasParent($('body')) //true
Run Code Online (Sandbox Code Playgroud)

#API:

// check if current element has parent element 'e' 
$.fn.hasParent = function (e) {
    return !!$(this).parents(e).length
}
Run Code Online (Sandbox Code Playgroud)

  • 我不认为感叹号应该在那里. (3认同)