在jQuery中获得下一个兄弟的最干净的方法 [英] Cleanest way to get the next sibling in jQuery

查看:59
本文介绍了在jQuery中获得下一个兄弟的最干净的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://jsfiddle.net/mplungjan/H9Raz/

在对next('a')进行了相当多的测试之后,我终于找到了一个可行的测试. 我只是想知道为什么next('a')没有,或者最接近或相似.单击复选框后,是否可以使用更干净的方法来获取链接的href?

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?

$('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>

推荐答案

要详细说明上面的评论:

To elaborate on the comments above:

  • next("a"),因为 next()仅尝试匹配下一个元素.它将击中<br>元素,但不匹配任何内容.

  • next("a"), because next() only tries to match the very next element. It will hit the <br> element and match nothing.

closest("a"),因为 closest()从上链开始元素本身,因此会错过<a>元素.

closest("a") , because closest() walks up the ancestor chain, starting with the element itself, and therefore will miss the <a> elements.

    正如Arend所建议的,
  • next().next().这可能是最快的解决方案,但是它使<br>元素成为必需.

  • next().next(), as Arend suggests. That's probably the fastest solution, but it makes the <br> elements mandatory.

nextAll("a"),但是它可以返回多个元素(并会与您的标记示例一起返回).链接到 first()可以阻止它,但是

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(),它仅遍历下一个同级直到找到链接,然后返回最后一个匹配元素的下一个同级. 可能要比nextAll()快,具体取决于您的标记.

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 might be faster than nextAll(), again, depending on your markup.

这篇关于在jQuery中获得下一个兄弟的最干净的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆