【问题标题】:How to navigate an array of items with buttons如何使用按钮导航一系列项目
【发布时间】:2021-10-05 23:50:50
【问题描述】:

如果我有一系列项目,我该如何浏览它们?让我们说两个按钮和一个 div 来显示我所在的当前索引?我只是写了一些我认为我需要但不知道逻辑的基本东西。

const items =[1,2,3]
let currentItem = 0

items.forEach((item, i) => console.log(item));


function next(){
currentItem++
}

function prev(){
currentItem--
}

<div>current index shown here<div>
<button onclick="next()">next item</button>
<button onclick="previous()">previous item</button>

【问题讨论】:

  • 您已经有了一个良好的开端!您的 currentItem 变量保存当前正在显示的任何项目。更准确地说,它保存了当前活动项的索引。现在假设您想要数组中的下一项,索引为 1。这意味着您需要在下一个函数中从 0 变为 1,例如只需将 +1 添加到 currentItem。试一试,我相信你能解决剩下的问题!
  • 我想我做到了,但感觉我还没有使用我的阵列?
  • 对不起,我完全错过了那部分 :) 你基本上完成了,它非常接近!你还有两件事要弄清楚。如果我正确理解您的代码,您想要显示当前索引(不是数组中该索引的值),因此您需要更改 div 的内容以显示currentItem(如果您想显示内容,您可以使用items[currentItem] 从数组中访问它。最后要做的是确保您的currentItem 不会超出数组大小的范围。看看下面的答案,看看是否你可以想办法!

标签: javascript arrays for-loop arraylist indexing


【解决方案1】:
const items =[1,2,3];
let currentIndex = 0;

function showCurrentIndex(i){
  if (currentIndex === 0 && i === -1){
     return false;
  }
  
  currentIndex = currentIndex + i;
  document.getElementById("yourDivId").innerHtml = currentIndex ;
}

<div id="yourDivId">current index shown here<div>
<button onclick="showCurrentIndex(1)">next item</button>
<button onclick="showCurrentIndex(-1)">previous item</button>

【讨论】:

    【解决方案2】:

    如果要在没有if条件的情况下循环遍历数组,可以使用如下方法:

    const output = document.querySelector('#output');
    const nextButton = document.querySelector('#next');
    const prevButton = document.querySelector('#prev');
    
    const items = [1, 2, 3, 4];
    let currentIndex = 0;
    
    const goToItem = (items, index) => {
      return (index + items.length) % items.length;
    };
    
    const handleNextClick = () => {
      currentIndex = goToItem(items, currentIndex + 1);
      output.innerHTML = `index: ${currentIndex}`;
    };
    
    const handlePrevClick = () => {
      currentIndex = goToItem(items, currentIndex - 1);
      output.innerHTML = `index: ${currentIndex}`;
    };
    
    nextButton.addEventListener('click', handleNextClick);
    prevButton.addEventListener('click', handlePrevClick);
    
    

    您的 HTML 可能看起来像

    <div id="output">current index shown here</div>
    <button id="next">next item</button>
    <button id="prev">previous item</button>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多