jQuery" hasParent" [英] jQuery "hasParent"

查看:85
本文介绍了jQuery" hasParent"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JQueryhas方法有效地选择了具有特定后代的所有元素。

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

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

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

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

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.

更新

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

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>

我有一个jQuery对象,已经包含元素2,3,4和5.我想要选择那些拥有class = x父级的元素。

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.

希望更有意义。

推荐答案

对于干净的可重用解决方案,请考虑使用用于确定特定祖先存在的自定义方法扩展 jQuery.fn 对象对于任何给定元素:

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

// 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;
        });
    }
});

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

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

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

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

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

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

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

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

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

这篇关于jQuery&quot; hasParent&quot;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆