这是标记:
<h2>
<a href="link1.html">text One for link One</a>
</h2>
<p> More text related to link one</p>
<h2>
<a href="link2.html">text Two for link Two</a>
</h2>
<p> More text related to link two</p>
<h2>
<a href="link3.html">text Three for link Three</a>
</h2>
<p> More text related to link three</p>
这是jQuery:
var prevLink = $(this).closest('h2').prev('h2').find('a').attr('href');
var nextLink = $(this).closest('h2').next('h2').find('a').attr('href');
.this
是初始链接。我的理解是,.closest
会将我带到父h2
标记,然后我会转到下一个和h2
标记。 .find
应该让我联系,最后.attr(href)
会告诉我属性。
现在,上一个和下一个元素可能不存在。为什么我无法获得正确的链接?我得到的只是undefined
。例如,如果我在link2.html
,我希望prevLink
为link1.html
而nextLink
为link3.html
。
感谢。
答案 0 :(得分:0)
.next()
/ .prev()
方法仅选择紧随其后的元素,这意味着如果h2
元素具有兄弟{{1},则不会选择任何内容介于两者之间的元素。
您可以使用p
/ .nextAll()
方法。然后链接.prevAll()
方法以获取集合中的第一个元素:
.first()