Javascript jQuery“hasParent”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2389540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:05:19  来源:igfitidea点击:

jQuery "hasParent"

javascriptjquery

提问by Chris Simpson

The JQuery "has" method effectively selects all elements where they have particular descendants.

JQuery 的“has”方法有效地选择了所有具有特定后代的元素。

I want to select elements based on the fact they have particular ancestors. I know about parent([selector]) and parents([selector]) but these select the parents and not the children with the parents.

我想根据元素具有特定祖先的事实来选择元素。我知道父母([选择器])和父母([选择器]),但这些选择父母而不是父母的孩子。

So is there an ancestor equivalent of "has"?

那么是否有一个相当于“has”的祖先?

Note:I already have the context of an element further down the hierarchy and I will be selecting based on this so I can't do a "top down" query.

注意:我已经有了层次结构更下方元素的上下文,我将基于此进行选择,因此我无法进行“自上而下”查询。

Update

更新

I've obviously explained myself really badly here, so I'll try and clarify:

显然,我在这里对自己的解释非常糟糕,所以我会尝试澄清:

<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>

I have a jQuery object that already consists of elements 2,3,4 and 5. I want to select those elements who have a parent with the class = x.

我有一个已经由元素 2、3、4 和 5 组成的 jQuery 对象。我想选择那些父元素为 class = x 的元素。

Hope that makes more sense.

希望这更有意义。

回答by Sampson

For a clean re-usable solution, consider extending the jQuery.fnobject with a custom method used for determining the presence of a particular ancestor for any given element:

对于干净的可重用解决方案,请考虑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;
        });
    }
});

This results in a new method, $.fn.within, that we can use to filter our results:

这产生了一种新方法 ,$.fn.within我们可以用它来过滤我们的结果:

$("li").within(".x").css("background", "red");

This selects all list items on the document, and then filters to only those that have .xas an ancestor. Because this uses jQuery internally, you could pass in a more complicated selector:

这将选择文档上的所有列表项,然后过滤到仅具有.x祖先的列表项。因为这在内部使用 jQuery,所以您可以传入一个更复杂的选择器:

$("li").within(".x, .y").css("background", "red");

This will filter the collection to items that descend from either .xor .y, or both.

这会将集合过滤为从.x.y或两者下降的项目。

Fiddle: http://jsfiddle.net/jonathansampson/6GMN5/

小提琴:http: //jsfiddle.net/jonathansampson/6GMN5/

回答by psychotik

if ( $('.foo').parents('.parentSelector').length ) { // has parent }

if ( $('.foo').parents('.parentSelector').length ) { // has parent }

回答by David Hellsing

If I understand your question correctly, this would do:

如果我正确理解你的问题,这会做:

$.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>

回答by Abdennour TOUMI

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

$('div#myDiv').hasParent($('body')) //true

#API:

#API:

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

回答by James Montagne

You can actually use filterdirectly (without a function calling closest) and it will have better performance. Simply use a selector that matches elements contained within .x:

你实际上可以filter直接使用(没有函数调用closest),它会有更好的性能。只需使用匹配包含在 中的元素的选择器.x

$("li").filter(".x *")

this also differs slightly from the closestsolutions suggested by others in that it will not match if the element itself has the given class but only if it is withinan element with that class.

这也与closest其他人建议的解决方案略有不同,因为如果元素本身具有给定的类,但仅当它具有该类的元素时,它将不匹配。

If matching an element with the class is desired as well, this could be modified slightly:

如果还需要将元素与类匹配,则可以稍微修改一下:

$("li").filter(".x, .x *")

$("li").filter(".x *").css("background", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>

回答by streetparade

Try this

尝试这个

ul.myList > li > a

This selector selects only links that are direct children of list elements, which are in turn direct children of elements that have the class myList.

此选择器仅选择作为列表元素的直接子元素的链接,而这些链接又是具有类 myList 的元素的直接子元素。

回答by Ed Fryed

object.each(function(){
    element = $(this);
    if(element.parent().hasClass("x")){
        //do stuff
    }
});

this will affect every item in your object that has parent .x

这将影响对象中具有父级 .x 的每个项目

回答by xec

I realize this is an old question, but I'm leaving this here for future visitors looking for something similar;

我意识到这是一个老问题,但我将把它留在这里供未来的访客寻找类似的东西;

There is a $.contains(container, contained)method which returns a boolean.

有一种$.contains(container, contained)返回布尔值的方法。

https://api.jquery.com/jQuery.contains/

https://api.jquery.com/jQuery.contains/

回答by Powerlord

The easy way is this:

简单的方法是这样的:

// all children of a specific parent match
$('parentSelector').children();

// All children matching a specific pattern, one level deep
$('parentSelector > childSelector');
// or
// $('parentSelector').children('childSelector');

// All children matching a specific pattern, multiple levels deep
$('parentSelector childSelector');
// or
// $('parentSelector').find('childSelector');

or did you really need something more complicated than that?

或者你真的需要比这更复杂的东西吗?

Edit: If you already have an element, you can combine this with the parent() command, like so:

编辑:如果您已经有一个元素,则可以将其与 parent() 命令结合使用,如下所示:

myElement.parents('parentSelector').find('childSelector'); // Will include self

回答by Timur Carpeev

Very simple way to do it

非常简单的方法

$('.x').find('li')