首页 > 解决方案 > 为什么“for循环”中的“for in”不能用每个对象值更改表单元素中的每个输入值

问题描述

大家好!
我想做一些对动态function()更改input所选表单中的每个值有用的Object东西,但遗憾的是我下面的示例代码只显示"pineapple"

document.getElementById("change-val").addEventListener("click", function(event) {
  let dataObj = {
    fruit1: "melon",
    fruit2: "mango",
    fruit3: "pineapple"
  };
  let FormInput = document.getElementsByTagName("input");

  for (let index = 0; index < FormInput.length; index++) {
      for (let keyObj in dataObj) {
          FormInput[index].value = dataObj[keyObj];       
      }
  }
});
<button id="change-val">Change Value</button>
<form>
  <input type="text" value="apple"/>
  <input type="text" value="watermelon"/>
  <input type="text" value="banana"/>
</form>

标签: javascripthtmlfor-loopdomecmascript-6

解决方案


你不应该使用嵌套循环。使用一个循环来获取具有索引的相应属性。

您可以使用Object.values()来获取属性值的数组。

document.getElementById("change-val").addEventListener("click", function(event) {
  let dataObj = {
    fruit1: "melon",
    fruit2: "mango",
    fruit3: "pineapple"
  };
  let FormInput = document.getElementsByTagName("input");
  let fruits = Object.values(dataObj);

  for (let index = 0; index < FormInput.length; index++) {
    FormInput[index].value = fruits[index];
  }
});
<button id="change-val">Change Value</button>
<form>
  <input type="text" value="apple" />
  <input type="text" value="watermelon" />
  <input type="text" value="banana" />
</form>


推荐阅读