【问题标题】:Trying to make "next" and "previous" buttons that loop through navigation onclick尝试制作循环通过导航的“下一个”和“上一个”按钮
【发布时间】:2019-08-22 21:59:39
【问题描述】:

试图在我的导航中制作“下一个”和“上一个”按钮。单击时,他们应该将我带到下一个/上一个 html 文件(网页)。

代码如下所示:

const pages =
["home.html","about.html","skills.html","projects.html","contact.html"];

const currentUrl = window.location.href;
const i = pages.indexOf(currentUrl) 
const arrowUp = document.getElementById("up");
const arrowDown = document.getElementById("down");

function next(){
    i++;

    let goTo = pages[i];

    window.location = goTo;

    if(i===pages.length){
        i = 0;
    }
}

function prev(){
    i--;

    let goTo = pages[i];

    window.location = goTo;

    if(i=0){
        i = pages.length;
    }
}

arrowUp.addEventListener("click",next());

arrowDown.addEventListener("click",prev());
<div id="arrows">
  <a href="#" id="up">
    <i class="far fa-arrow-circle-up"></i>
  </a>
  <a href="#" id="down" class="mbot1">
    <i class="far fa-arrow-circle-down"></i>
  </a>
</div>

链接问题是因为href="#"吗?点击它只是在当前 url 上添加 # (就像没有 js 一样)。

【问题讨论】:

  • 您对i === pages.length 的测试需要在let goTo = pages[i]; 之前进行。您对 应该 i === 0 而不是 i = 0 的测试存在同样的问题。

标签: javascript html


【解决方案1】:

您正在用const 声明i。那就不能重新分配了。使用var或let

var i = pages.indexOf(currentUrl)

【讨论】:

    【解决方案2】:

    代码存在一些问题。

    首先,i 是用const 声明的,但如果您想稍后再设置它,则需要用let 或var 声明。您还要检查 i 是否等于 0 和 =,这将设置它,而不是比较运算符 == 或 ===。

    您的初始i 值的另一个问题是,如果在pages 中找不到currentUrl,它可能设置为-1。除非您确定您将始终拥有pages.indexOf(currentUrl) &gt;= 0,否则您应该添加默认/备用值。

    导航后还会检查开始和结束限制。问题是如果你是home.html(索引0),你会递减,导航到索引-1,然后设置i = pages.length。您应该使用 if/else 语句来设置i,或者简称为三元运算符。

    最后,pages.length 将您的指针设置为超过现有索引的位置。在您的示例中,pages 包含五个项目,但由于数组索引从 0 开始,因此最后一个位于 pages[4]。 pages[5] 不存在。

    试试这个代码:

    function next(){
        i = i === pages.length - 1 // if index at end
            ? 0                    // go to start
            : i + 1;               // else go next
        let goTo = pages[i];
        window.location = goTo;
    }
    
    function prev(){
    
        i = i === 0            // if index is at start
            ? pages.length - 1 // go to end
            : i - 1;           // else go back one
        let goTo = pages[i];
        window.location = goTo;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多