查找最近的上一个元素 jQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7018337/
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
Find closest previous element jQuery
提问by Peter Olson
I am wanting something similar to this person, except the element I want to match might not be a direct sibling.
我想要类似于这个person 的东西,除了我想要匹配的元素可能不是直接兄弟。
If I had this HTML, for example,
例如,如果我有这个 HTML,
<h3>
<span>
<b>Whaddup?</b>
</span>
</h3>
<h3>
<span>
<b>Hello</b>
</span>
</h3>
<div>
<div>
<img />
</div>
<span id="me"></span>
</div>
<h3>
<span>
<b>Goodbye</b>
</span>
</h3>
I would want to be able to do something like this:
我希望能够做这样的事情:
var link = $("#me").closestPreviousElement("h3 span b");
console.log(link.text()); //"Hello"
Is there an easy way to do this in jQuery?
有没有一种简单的方法可以在 jQuery 中做到这一点?
EDIT: I should have made my specification a little bit clearer. $("#me")
may or may not have a parent div. The code should not assume that it does. I don't necessarily know anything about the surrounding elements.
编辑:我应该让我的规范更清楚一点。$("#me")
可能有也可能没有父 div。代码不应假设它确实如此。我不一定对周围的元素一无所知。
回答by user113716
var link = $("#me").closest(":has(h3 span b)").find('h3 span b');
Example:http://jsfiddle.net/e27r8/
示例:http : //jsfiddle.net/e27r8/
This uses the closest()
[docs]method to get the first ancestor that has a nested h3 span b
, then does a .find()
.
这使用closest()
[docs]方法获取具有嵌套 的第一个祖先h3 span b
,然后执行.find()
.
Of course you could have multiple matches.
当然,您可以有多个匹配项。
Otherwise, you're looking at doing a more direct traversal.
否则,您正在考虑进行更直接的遍历。
var link = $("#me").closest("h3 + div").prev().find('span b');
edit: This one works with your updated HTML.
编辑:这个适用于您更新的 HTML。
Example:http://jsfiddle.net/e27r8/2/
示例:http : //jsfiddle.net/e27r8/2/
EDIT:Updated to deal with updated question.
编辑:更新以处理更新的问题。
var link = $("#me").closest("h3 + *").prev().find('span b');
This makes the targeted element for .closest()
generic, so that even if there is no parent, it will still work.
这使得目标元素为.closest()
泛型,因此即使没有父元素,它仍然可以工作。
Example:http://jsfiddle.net/e27r8/4/
回答by Emil
see http://api.jquery.com/prev/
var link = $("#me").parent("div").prev("h3").find("b");
alert(link.text());
回答by gilly3
No, there is no "easy" way. Your best bet would be to do a loop where you first check each previous sibling, then move to the parent node and all of its previous siblings.
不,没有“简单”的方法。最好的办法是做一个循环,首先检查每个以前的兄弟节点,然后移动到父节点及其所有以前的兄弟节点。
You'll need to break the selector into two, 1 to check if the current node could be the top level node in your selector, and 1 to check if it's descendants match.
您需要将选择器分成两部分,1 用于检查当前节点是否可能是选择器中的顶级节点,1 用于检查它的后代是否匹配。
Edit:This might as well be a plugin. You can use this with any selector in any HTML:
编辑:这也可能是一个插件。你可以在任何 HTML 中的任何选择器中使用它:
(function($) {
$.fn.closestPrior = function(selector) {
selector = selector.replace(/^\s+|\s+$/g, "");
var combinator = selector.search(/[ +~>]|$/);
var parent = selector.substr(0, combinator);
var children = selector.substr(combinator);
var el = this;
var match = $();
while (el.length && !match.length) {
el = el.prev();
if (!el.length) {
var par = el.parent();
// Don't use the parent - you've already checked all of the previous
// elements in this parent, move to its previous sibling, if any.
while (par.length && !par.prev().length) {
par = par.parent();
}
el = par.prev();
if (!el.length) {
break;
}
}
if (el.is(parent) && el.find(children).length) {
match = el.find(children).last();
}
else if (el.find(selector).length) {
match = el.find(selector).last();
}
}
return match;
}
})(jQuery);
回答by jgibbs
I know this is old, but was hunting for the same thing and ended up coming up with another solution which is fairly concise andsimple. Here's my way of finding the next or previous element, taking into account traversal over elements that aren't of the type we're looking for:
我知道这是旧的,但正在寻找同样的东西,最终想出了另一个相当简洁和简单的解决方案。这是我查找下一个或上一个元素的方法,考虑到遍历不是我们正在寻找的类型的元素:
var ClosestPrev = $( StartObject ).prevAll( '.selectorClass' ).first();
var ClosestNext = $( StartObject ).nextAll( '.selectorClass' ).first();
I'm not 100% sure of the order that the collection from the nextAll/prevAll functions return, but in my test case, it appears that the array is in the direction expected. Might be helpful if someone could clarify the internals of jquery for that for a strong guarantee of reliability.
我不是 100% 确定 nextAll/prevAll 函数的集合返回的顺序,但在我的测试用例中,数组似乎是在预期的方向上。如果有人可以为此澄清 jquery 的内部结构以强有力地保证可靠性,这可能会有所帮助。
回答by RobB
var link = $("#me").closest(":has(h3 span b)").find('span b').text();
var link = $("#me").closest(":has(h3 span b)").find('span b').text();