Cleanest way to get the next sibling in jQuery

╄→尐↘猪︶ㄣ 提交于 2019-12-17 18:34:02

问题


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?

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

回答1:


To elaborate on the comments above:

You cannot write:

  • 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 can write:

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




回答2:


Or, you could just use the jQuery built-in function .siblings()

https://api.jquery.com/siblings/




回答3:


Below code worked for me

$('#id ~ iframe');



来源:https://stackoverflow.com/questions/6237673/cleanest-way-to-get-the-next-sibling-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!