2013-10-11 15 views
2

我目前正在使用ajax在單擊錨點鏈接時拉取內容的網站上工作。我希望使用一組預定義的頁面鏈接創建一個自定義的next/prev按鈕。使用anchor .attr href作爲數組的起點在計數器中

我試圖使用一個數組作爲計數器來移動通過頁面時,單擊下一個按鈕。但我想使用當前的href屬性作爲起點,然後通過正負數組來移動數組,取決於哪個按鈕被點擊。

這裏的電流codepen我正在http://codepen.io/veryrobert/pen/ocIhl

HTML:

<a id="value1" href="one.html">NEXT</a> 
<a id="value2" href="">PREV</a> 

的Jquery:

$(function(){ 

    var pages = [ "one.html", "two.html", "three.html", "four.html" ]; 
    var prev = "#value2"; 
    var next = "#value1"; 

    // This works as a starting point 
    counter = 0; 

    // But I'd really like this to be the starting point 
    // counter = $(next).attr("href"); 

    $(next).click(function(e){ 
    e.preventDefault(); 
    counter = (counter + 1) % pages.length; 

    }); 

    $(prev).click(function(e){ 
    e.preventDefault(); 
    counter = (counter - 1) % pages.length; 
    $(prev).attr("href", counter); 
    }); 


}); 

我不是真正偉大的一個JavaScript,請如果這見諒是一種愚蠢的做法,或者我正在以完全錯誤的方式去解決這個問題。

所有幫助真的讚賞advacnce

感謝

+0

不能確定你的要求,你想一個更好的辦法來遍歷上點擊一個數組? –

+0

我想將我的a標籤的href值與數組聯繫起來 – veryrobert

+0

這可以完成。搜索有關解析URLS的帖子。如何做一個單頁面的應用程序(SPA)並附加一個URL參數呢? http://mycoolexamplesite.com?page=1 – isherwood

回答

0

你可以試試這個

function getCounter(element, array) { 

    var href = element.getAttribute('href'); 

    for (var i=0; i < array.length; i++) { 

     if (array[i] === href) { 
      return i; 
     } 

    } 

    return -1; 

} 

你使用這樣的:

counter = getCounter(document.getElementById(next), pages); 

注:如果您打算使用jQuery我不確定當你調用$(next).attr('href')時它會返回什麼。 element.getAttribute('href')將返回「one.html」,但 element.href將返回「host.com/one.html」

相關問題