jQuery 中是否有一种方法可以从元素向上遍历 dom 树并在其父元素之前检查选择器



例如:

<div class="mainWrapper">
    <div class="FirstLayer">
        <input class="foo" value="foo" />
    </div>
    <div class="SecondLayer">
        <div class="thirdLayer">
            <input class="fee" />
        </div>
    </div>
</div>

假设我将input.fee作为 jQuery 对象,并且还需要获取 input.foo 的值。现在我知道我可以使用多种方法,例如$(this).parents(':eq(2)').find('.foo')但我想在具有不同级别和节点数量的布局上使用这种方法。所以我想知道是否有一种方法可以简单地从.fee开始,然后继续上升直到找到第一个匹配元素,.prevAll()似乎没有这样做。有许多.foo.fee元素,我特别需要上下文中.fee上方的第一个元素。

这个怎么样:

$('input.fee').closest(':has("input.foo")')
              .find('input.foo').val();

这是JS小提琴可以玩的。

更新:向@VisioN致敬 - 当然,parents:firstclosest很好地取代了。

这将选择上一个 input.foo

// self might have siblings that are input.foo so include in selection
$( $("input.fee").parentsUntil(":has(input.foo)").andSelf()
        // if input.off is sibling of input.fee then nothing will
        // be returned from parentsUntil. This is the only time input.fee
        // will be selected by last(). Reverse makes sure self is at index 0
        .get().reverse() )
        // last => closest element
        .last()                 
        //fetch siblings that contain or are input.foo elements
        .prevAll(":has(input.foo), input.foo") 
        // first is closest
        .first() 
        // return jQuery object with all descendants
        .find("*")         
        // include Self in case it is an input.foo element 
        .andSelf() 
        .filter("input.foo")
        // return value of first matching element
        .val() 

jQuery.closest()采用选择器并完全按照您的要求执行任务 - 找到作为某物父级的第一个匹配元素。还有jQuery.parents()确实需要一个选择器来过滤元素祖先。将这些与find方法结合使用,即可设置好。

$('input.fee').closest('.mainWrapper").find('.foo')诀窍,不是吗?

最新更新