在 jQuery 中获取下一个兄弟的最简洁方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6237673/
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
Cleanest way to get the next sibling in jQuery
提问by mplungjan
http://jsfiddle.net/mplungjan/H9Raz/
http://jsfiddle.net/mplungjan/H9Raz/
After quite some tests with next('a') and such, I finally found one that worked. I just wonder why next('a') did not, or closest or similar. Are there cleaner ways to get at the href of the link after the checkbox I click?
在对 next('a') 等进行了相当多的测试之后,我终于找到了一个有效的方法。我只是想知道为什么 next('a') 没有,或者最接近或相似。在单击复选框后,是否有更简洁的方法来获取链接的 href?
$('form input:checkbox').click(function () {
alert($(this).nextAll('a').attr("href"));
});
<form>
<div>
<input type="checkbox" name="checkThis" value="http://www.google.com" />Check here<br/>
<a href="http://www.google.com">click here</a><br>
<input type="checkbox" name="checkThis" value="http://www.bing.com" />Check here<br/>
<a href="http://www.bing.com">click here</a>
</div>
</form>
回答by Frédéric Hamidi
To elaborate on the comments above:
详细说明上面的评论:
You cannotwrite:
你不能写:
next("a")
, because next()only tries to match the very next element. It will hit the<br>
element and match nothing.closest("a")
, because closest()walks up the ancestor chain, starting with the element itself, and therefore will miss the<a>
elements.
You canwrite:
你可以写:
next().next()
, as Arend suggests. That's probably the fastest solution, but it makes the<br>
elements mandatory.nextAll("a")
, but that can return multiple elements (and will do so with your markup sample). Chaining into first()would prevent it, but nextAll()still would have to iterate over all the next siblings, which can make it slow depending on the complexity of the markup inside your<div>
elements.nextUntil("a").last().next()
, which only iterates over the next siblings until it finds a link, then returns the immediate next sibling of the last element matched. It mightbe faster thannextAll()
, again, depending on your markup.
回答by Peter Graham
Or, you could just use the jQuery built-in function .siblings()
或者,您可以只使用 jQuery 内置函数 .siblings()
回答by Ricky
Below code worked for me
下面的代码对我有用
$('#id ~ iframe');
$('#id ~ iframe');