寻找包含当前节点的 jQuery find(..) 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2828019/
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-26 14:20:48  来源:igfitidea点击:

Looking for jQuery find(..) method that includes the current node

jquery

提问by John K

The jQuery find(..)traversal method doesn't include the current node - it starts with the children of the current node. What is the best way to call a find operation that includes the current node in its matching algorithm? Looking through the docs nothing immediately jumps out at me.

jQuery find(..)遍历方法不包括当前节点——它从当前节点的子节点开始。调用在其匹配算法中包含当前节点的查找操作的最佳方法是什么?翻阅文档,没有什么会立即跳到我身上。

回答by Robert

For jQuery 1.8 and up, you can use .addBack(). It takes a selector so you don't need to filter the result:

对于 jQuery 1.8 及更高版本,您可以使用.addBack(). 它需要一个选择器,因此您无需过滤结果:

object.find('selector').addBack('selector')

Prior to jQuery 1.8 you were stuck with .andSelf(), (now deprecated and removed) which then needed filtering:

在 jQuery 1.8 之前,您一直使用.andSelf(), (现已弃用并删除),然后需要过滤:

object.find('selector').andSelf().filter('selector')

回答by Nick Craver

You can't do this directly, the closest I can think of is using .andSelf()and calling .filter(), like this:

您不能直接执行此操作,我能想到的最接近的是使用.andSelf()和调用.filter(),如下所示:

$(selector).find(oSelector).andSelf().filter(oSelector)
//or...
$(selector).find('*').andSelf().filter(oSelector);

Unfortunately .andSelf()doesn't take a selector, which would be handy.

不幸的.andSelf()是没有选择器,这会很方便。

回答by Dmitriy Sintsov

Define

定义

$.fn.findSelf = function(selector) {
    var result = this.find(selector);
    this.each(function() {
        if ($(this).is(selector)) {
            result.add($(this));
        }
    });
    return result;
};

then use

然后使用

$.findSelf(selector);

instead of

代替

$find(selector);

Sadly jQuery does not have this built-in. Really strange for so many years of development. My AJAX handlers weren't applied to some top elements due to how .find() works.

遗憾的是 jQuery 没有这个内置功能。这么多年的发展真的很奇怪。由于 .find() 的工作方式,我的 AJAX 处理程序没有应用于某些顶级元素。

回答by Tgr

$('selector').find('otherSelector').add($('selector').filter('otherSelector'))

You can store $('selector')in a variable for speedup. You can even write a custom function for this if you need it a lot:

您可以存储$('selector')在变量中以加快速度。如果您非常需要,您甚至可以为此编写自定义函数:

$.fn.andFind = function(expr) {
  return this.find(expr).add(this.filter(expr));
};

$('selector').andFind('otherSelector')

回答by erikrestificar

The accepted answer is very inefficient and filters the set of elements that are already matched.

接受的答案非常低效,并过滤了已经匹配的元素集。

//find descendants that match the selector
var $selection = $context.find(selector);
//filter the parent/context based on the selector and add it
$selection = $selection.add($context.filter(selector);

回答by oriadam

In case you are looking for exactly one element, either current element or one inside it, you can use:

如果您正在寻找一个 element,无论是当前元素还是其中的一个,您可以使用:

result = elem.is(selector) ? elem : elem.find(selector);

In case you are looking for multiple elementsyou can use:

如果您正在寻找多个元素,您可以使用:

result = elem.filter(selector).add(elem.find(selector));

The use of andSelf/andBackis pretty rare, not sure why. Perhaps because of the performance issues some guys mentioned before me.

andSelf/的使用andBack非常罕见,不知道为什么。也许是因为一些人在我之前提到的性能问题。

(I now noticed that Tgralready gave that second solution)

(我现在注意到Tgr已经给出了第二个解决方案)

回答by SeregPie

If you want the chaining to work properly use the snippet below.

如果您希望链接正常工作,请使用下面的代码段。

$.fn.findBack = function(expr) {
    var r = this.find(expr);
    if (this.is(expr)) r = r.add(this);
    return this.pushStack(r);
};

After the call of the end function it returns the #foo element.

在调用结束函数后,它返回#foo 元素。

$('#foo')
    .findBack('.red')
        .css('color', 'red')
    .end()
    .removeAttr('id');

Without defining extra plugins, you are stuck with this.

如果没有定义额外的插件,你就会陷入困境。

$('#foo')
    .find('.red')
        .addBack('.red')
            .css('color', 'red')
        .end()
    .end()
    .removeAttr('id');

回答by Justin Warkentin

I know this is an old question, but there's a more correct way. If order is important, for example when you're matching a selector like :first, I wrote up a little function that will return the exact same result as if find()actually included the current set of elements:

我知道这是一个老问题,但有一个更正确的方法。如果顺序很重要,例如当你匹配一个选择器时:first,我写了一个小函数,它会返回与find()实际包含当前元素集完全相同的结果:

$.fn.findAll = function(selector) {
  var $result = $();

  for(var i = 0; i < this.length; i++) {
    $result = $result.add(this.eq(i).filter(selector));
    $result = $result.add(this.eq(i).find(selector));
  }

  return $result.filter(selector);
};

It's not going to be efficient by any means, but it's the best I've come up with to maintain proper order.

无论如何它都不会有效率,但这是我想出的最好的方法来维持适当的秩序。

回答by mikewasmike

If you are strictly looking in the current node(s) the you just simply do

如果您严格查看当前节点,则只需执行

$(html).filter('selector')

回答by interjay

I think andSelfis what you want:

我认为andSelf是你想要的:

obj.find(selector).andSelf()

Note that this will always add back the current node, whether or not it matches the selector.

请注意,这将始终添加回当前节点,无论它是否与选择器匹配。