javascript - 为什么“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>
解决方案
你不应该使用嵌套循环。使用一个循环来获取具有索引的相应属性。
您可以使用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>
推荐阅读
- spring-boot - 错误:无法找到或加载主类 com.spring.solarlog.netflixeurekanamingserver.NetflixEurekaNamingServerApplication
- youtube - 使用访问令牌的 Youtube-api 非常小的配额
- ms-word - 如何将 VB6 表单停靠在 MS Word 任务窗格上?
- reactjs - React Routes v4 的行为因索引而异
- php - 在所有页面上显示文本
- javascript - 如何用截止日期显示结束日期 31-03
- c# - 无法让 Autofac 使用 Web API 2
- python - 将多嵌套的 dict/json 加载到 pandas 中
- java - 在 Spring Boot 中将日期作为请求参数处理错误
- rxjs - Rxjs 和 .pipe 的区别