且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在jQuery中获得下一个兄弟的最干净的方法

更新时间:2022-02-14 22:43:25

要详细说明上面的评论:

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.