如何使用纯 javascript 遍历每个 div 标签?

问题描述

我有一段代码,当我按回车键时,它会循环遍历 div。

""

但是控制台会记录如下内容:0 1 2 3 4...
我希望每次按回车键时都记录每个新索引。所以它会像:0(输入)1(输入)2(输入)3...
我该怎么做?

解决方法

您可以创建一个处理函数来设置 index 变量,并缓存 div,然后返回一个新函数(称为 closure),每当事件发生。

function handler() {

  // Create the index and divs variable.
  // These variables will be carried into the closure
  let index = 0;
  const divs = document.querySelectorAll('div');

  // Because the closure maintains references
  // to the variables in its "outer lexical environment"
  // you can update them when it's returned from the handler
  return function () {

    // Now just check to see if the index value is
    // less than the length of the collection of elements
    // If it is log the value,and increase the index
    if (index < divs.length) {
      console.log(index);
      index++;
    } else {
      console.log('Nothing to log');
    }
  }
}

const keywords = document.querySelector('#keywords')

// Call the handler function so that the the variables
// can be initiated,and the closure that the listener will be
// using can be returned
keywords.addEventListener('keyup',handler(),false);
<input type="text" id="keywords"></input>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>

,

window.onload = () => {
  let keyword = document.getElementById('keywords');
  var enterCount = 0;
  var divs = document.getElementsByTagName('span');
  keyword.addEventListener('keyup',function(e) {
    if (e.key === 'Enter') {
      if (enterCount < divs.length) {
        console.log(enterCount);
        enterCount += 1;
      }
    }
  })

}
<input type="text" id="keywords"></input>
<span>123</span>
<span>345</span>
<span>567</span>

我认为您正在寻找这样的东西。您可以将 span 标签更改为您的 div。此 span 标记仅用于示例目的。