简体   繁体   English

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

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

I'm currently working on a site that is using ajax to pull content in when an anchor link is clicked. 我目前正在使用单击锚点链接时使用ajax提取内容的网站。 I'm hoping to create a custom next/prev button using an array of predefined page links. 我希望使用一系列预定义的页面链接来创建自定义的下一个/上一个按钮。

I'm trying to use a array as a counter to move through the pages when the next button is clicked. 我正在尝试使用数组作为计数器,以在单击下一个按钮时在页面之间移动。 But I would like to use the current href attribute as a starting point then would move through the array by plus or minus one depend which button is click. 但是我想使用当前的href属性作为起点,然后通过加号或减号(取决于单击哪个按钮)在数组中移动。

Here's the current codepen I'm working on http://codepen.io/veryrobert/pen/ocIhl 这是我正在使用的当前Codepen http://codepen.io/veryrobert/pen/ocIhl

HTML: HTML:

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

Jquery: 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 ); 
   }); 


});

I'm not really great a javascript so please forgive me if this is a stupid approach or I'm going about this completely the wrong way. 我不是一个很棒的JavaScript程序员,所以如果这是一种愚蠢的方法,或者我将以完全错误的方式进行操作,请原谅我。

All help is really appreciated 非常感谢所有帮助

Thanks in advacnce 感谢您的到来

You can try this 你可以试试这个

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;

}

You use it like this: 您可以这样使用它:

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

Note: If you intend to use jQuery I am not sure what it returns when you call $(next).attr('href') . 注意:如果您打算使用jQuery,则不确定在调用$(next).attr('href') element.getAttribute('href') would return 'one.html' but element.href would return 'host.com/one.html' 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