首页 > 解决方案 > 使用循环标记多个元素

问题描述

我目前正在尝试使用循环遍历多个输入框,但我不知道该怎么做。

我的 JS 代码:

function tagger() {
  var t;
  for (t = 0; t < 5; t++) {
    document.getElementsByClassName("pl")[0].getElementsByTagName("input")
  }
};
return tagger();

HTML:

 <h1 class="pizza">Pineapple</h1>
  <body class="maco">
    <div class="keys">
      <span class="press"  onclick="car()"><i class="fas fa-fingerprint"></i><h2>Log In</h2></span>
      <span class="type" id="heyu"><input class="entry" placeholder="Password"></span>
    </div>
  </body>
</html>

提前感谢您提供的任何帮助!

标签: javascriptfunctionloopsinputlabel

解决方案


您必须将 t 变量添加为 (getElementsByTagName) 的索引

document.getElementsByClassName("pl")[0].getElementsByTagName("input")[t];

或者您可以使用 forEach 方法是循环槽数组的最佳方法

function tragger  () {
  var _Element = Array.from(document.querySelector("pl input"));
  _Element.forEach(function (ele) {
     //do some code for each input
     ele.value = 'etc';
  });
  }
tragger();

推荐阅读