jquery $(this).prev(".class") 不起作用

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

jquery $(this).prev(".class") not working

jqueryjquery-selectors

提问by Pedro

Given this simple setup

鉴于这个简单的设置

<div class="parent">
   <div class="child">I'm spoiled</div>
</div>
<div class="aunt"></div>
<div class="uncle"></div>

<div class="parent">
   <div class="child">I'm spoiled</div>
</div>
<div class="aunt"></div>
<div class="uncle"></div>

When I detect a click on class "uncle", I want to get the sibling of the closest previous ".parent". I should be able to do

当我检测到对“叔叔”类的点击时,我想获得最近的“.parent”的兄弟姐妹。我应该能够做到

$( this ).prev( ".parent" ).children( ".child" ).text();

...but this returns a blank.

...但这会返回一个空白。

If I do

如果我做

$( this ).prev().prev().children( ".child" ).text();

...this returns the expected result: "I'm spoiled"

...这将返回预期的结果:“我被宠坏了”

Is there some limitations to the use of prev( [selector] ) I'm missing?

我遗漏的 prev( [selector] ) 的使用有一些限制吗?

[UPDATE]

[更新]

.prevAll() returns all previuos classes, so the result of

.prevAll() 返回所有以前的类,所以结果

$( this ).prevAll( ".parent" ).children( ".child" ).text();

Is "I'm spoiledI'm spoiled" if I click on the second ".uncle", which is not the result I want.

如果我点击第二个“.uncle”是“我被宠坏了我被宠坏了”,这不是我想要的结果。

I just need the immediate closest previous one.

我只需要最接近的前一个。

回答by George

From the jquery documentation:

从 jquery 文档:

.prev() Description: Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.

.prev() 描述:获取匹配元素集中每个元素的前一个兄弟元素,可选地由选择器过滤。

Also:

还:

To select all preceding sibling elements, rather than just the preceding adjacent sibling, use the .prevAll() method.

要选择所有前面的同级元素,而不仅仅是前面的相邻同级元素,请使用 .prevAll() 方法。

So, there you go, use the .prevAll() method instead. http://api.jquery.com/prev/

所以,你去了,改用 .prevAll() 方法。 http://api.jquery.com/prev/

回答by Joseph Marikle

That's because that's not what prev was intended to do. You are trying to use prev in the way .prevAll() is supposed to work.

那是因为这不是 prev 的意图。您正在尝试以 .prevAll() 应该工作的方式使用 prev。

EDIT:

编辑:

Considering your latest requirements, I would think something like this would work:

考虑到您的最新要求,我认为这样的事情会起作用:

$(this).prevUntil(".parent").first().prev().children( ".child" ).text()

回答by panupan

prev() returns only the first preceeding element.

prev() 只返回第一个前面的元素。

Try:

尝试:

$( this ).prevAll( ".parent:first" ).children( ".child" ).text();

回答by Lukas

this may be better way:

这可能是更好的方法:

var this = $(this);
var.parent('.parent').prev().children('.children').text();