使用锚点 .attr href 作为计数器中数组的起点

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

本文关键字:计数器 数组 起点 attr href      更新时间:2023-09-26

>我目前正在开发一个使用 ajax 在单击锚链接时拉入内容的网站。我希望使用预定义的页面链接数组创建自定义的下一个/上一个按钮。

我尝试使用数组作为计数器,以便在单击下一个按钮时在页面中移动。但是我想使用当前的 href 属性作为起点,然后在数组中移动加减一,具体取决于单击哪个按钮。

这是我正在处理的当前代码笔 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')会返回"一.html",但 element.href会返回"host.com/one.html">