【问题标题】:How can I loop through the each div tag with pure javascript?如何使用纯 JavaScript 遍历每个 div 标签?
【发布时间】:2021-10-06 05:26:20
【问题描述】:

当我按下回车键时,我有这段代码循环遍历 div。

<input type="text" id="keywords"></input>

document.getElementById("keywords").addEventListener("keyup", function(e) {
    if (e.key === 'Enter') {
        var element = document.getElementsByTagName("mark");
    
        for (var y=0; y<element.length; y++) {
            console.log(y);
        }
        }
        
    }, false);

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

【问题讨论】:

  • 你想做什么?为什么你需要document.getElementsByTagName
  • @Unmitigated 我正在像 ctrl+f 一样进行搜索,我正在尝试弄清楚如何使用它来执行输入功能。如果用户在输入中键入内容并且关键字与页面上的某个单词匹配,则页面上的单词将被包装到自定义 html 标记“mark”中。在这种情况下,这就是我检测页面上有多少匹配关键字的方法。 (当我问一个问题时,每个人都对“mark”标签感到非常困惑,我认为如果我将其更改为“div”会更容易,但我想它也很混乱,所以我只是将它保留为“mark”。它没有无论如何,我的问题是关于循环的。)
  • 不能直接将值添加到数组中,还是“mark”元素有特殊用途?你是在强调事情吗?设置一些CSS? @Maroun

标签: javascript arrays for-loop foreach


【解决方案1】:

您可以创建一个处理函数来设置index 变量并缓存divs,然后返回一个新函数(称为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>

【讨论】:

  • 我编辑了问题并添加了解释我想要做什么的评论
【解决方案2】:

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 标签仅用于示例目的。

【讨论】:

  • 所以我将 for 循环更改为 if 语句,就像您的代码中一样,但每次我按 Enter 时它只会记录零,因此它实际上不会遍历标签
  • 变量count如何保存计数的数量。您是否也添加了那部分@Maroun?
猜你喜欢
  • 2021-09-05
  • 2021-10-04
  • 2016-10-14
  • 2011-08-14
  • 1970-01-01
  • 2014-07-03
  • 2022-01-18
  • 2020-06-02
  • 2014-03-20
相关资源
最近更新 更多