簡體   English   中英

使用錨.attr href作為計數器中數組的起點

[英]Use anchor .attr href as a starting point for an array in a counter

我目前正在使用單擊錨點鏈接時使用ajax提取內容的網站。 我希望使用一系列預定義的頁面鏈接來創建自定義的下一個/上一個按鈕。

我正在嘗試使用數組作為計數器,以在單擊下一個按鈕時在頁面之間移動。 但是我想使用當前的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程序員,所以如果這是一種愚蠢的方法,或者我將以完全錯誤的方式進行操作,請原諒我。

非常感謝所有幫助

感謝您的到來

你可以試試這個

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM