2011-01-04 2 views
4

에서 다음 및 이전 링크를 찾기 :이 같은 목록 요소에 중첩 된 링크 계층 구조가 계층 구조

<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> 

기본적으로 단지 사이트 맵을. 하지만 jQuery를 사용하여 다음 및 이전 링크를 만들고 싶습니다.이 페이지는 현재 클래스를 확인하여 활성 페이지를 찾고 이전 및 다음 앵커 요소를 찾습니다 (계층 구조를 고려하지 않음). next(), previous()find()으로 시도했지만 제대로 작동하지 않는 것 같습니다.

현재 앵커 요소를 가져 오는 가장 쉬운 방법은 무엇입니까?

답변

6
var selected = $("a.selected"); 
var anchors = $("a"); 

var pos = anchors.index(selected); 
var next = anchors.get(pos+1); 
var prev = anchors.get(pos-1); 
+0

을 내가 두 번째 줄은 앵커 = $ ('A'를) be..var해야한다고 생각; – Vivek

+0

@vivek : 정확합니다, 감사합니다! – Gregoire

+0

와우, 그렇게 간단합니다. 놀랍게도 작은 코드. 감사! –

7

가정하고 <a> 현재 페이지가 class="current"을 가지고 들어, 당신은 사이트 맵 내에 현재 페이지의 평탄화 된 인덱스 찾기 위해이 작업을 수행 할 수 있습니다 I가 3 줄에 위의 분할

// 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); 

을 설명의 목적이 있지만 위의 코드를 다음과 같이 짧게 만들 수 있습니다.

var i = $("ul a").index($("a.current")); 

그런 다음 페이지를 다음 및 p로 탐색 할 수 있습니다 레브 링크 :

마지막으로
// 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);