Find next and previous link in hierarchy
I have a hierarchy with links nested in a list item like this:
<ul>
<li><a href="#">Page 1</a>
<ul>
<li><a href="#">Page 1.1</a></li>
<li><a href="#">Page 1.2</a>
<ul>
<li><a href="#">Page 1.2.1</a></li>
<li><a href="#">Page 1.2.2</a></li>
</ul>
</li>
<li><a href="#">Page 1.3</a></li>
</ul>
</li>
<li><a href="#">Page 2</a>
<ul>
<li><a href="#">Page 2.1</a></li>
<li><a href="#">Page 2.2</a></li>
</ul>
</li>
<li><a href="#">Page 3</a>
<ul>
<li><a href="#">Page 3.1</a>
<ul>
<li><a href="#">Page 3.1.1</a></li>
<li><a href="#">Page 3.1.2</a></li>
</ul>
<li><a href="#">Page 3.2</a></li>
<li><a href="#">Page 3.3</a></li>
<ul>
<li><a href="#">Page 3.1.1</a></li>
<li><a href="#">Page 3.1.2</a></li>
</ul>
</li>
</ul>
</li>
</ul>
Basically just a sitemap. But I want to make the following and previous links with jQuery, which finds the active page you are on (possibly checking the class), and find the previous and next anchor element (not paying attention to the hierarchy). I tried with next(), previous()and find(), but can't get it to work.
What is the easiest way to get anchor elements before and after the current?
+5
2 answers
, <a> class="current", , :
// Get current anchor
var currentA = $("a.current");
// Get array of all anchors in sitemap
var anchors = $("ul a"); // (would be better if you gave the ul an id)
// Find the index of the current anchor, within the (flattened) sitemap
var i = anchors.index(currentA);
3 , :
var i = $("ul a").index($("a.current"));
:
// Go to the next link
function goToNext() {
if (i + 1 < anchors.length) {
window.location.href = anchors[i + 1].href;
}
}
// Go to the previous link
function goToPrev() {
if (i > 0) {
window.location.href = anchors[i - 1].href;
}
}
, :
$("a.next").click(goToNext);
$("a.prev").click(goToPrev);
+7