简体   繁体   English

使用 forEach 或 for 循环 (JS) 从 JSON 提要填充表单字段

[英]Populating form fields from JSON feed using forEach or for loop (JS)

I have form fields like these我有这样的表单字段

<input id="first">
<input id="second">
<textarea id="third"></textarea>
...

and I need to dynamically populate them with data from a JSON feed.我需要用来自 JSON 提要的数据动态填充它们。 Each field's id corresponds to each JSON's key , so I'm able to populate those fields this way:每个字段的 id 对应于每个 JSON 的 key ,所以我可以这样填充这些字段:

first.value = feed.first;
second.value = feed.second;
third.value = feed.third;
...

But I would like to make it simpler.但我想让它更简单。

This is what I've tried:这是我试过的:

["first", "second", "third"].forEach(e => {e.value = feed[e]});

Sadly, it doesn't work.可悲的是,它不起作用。 In console I can see JSON feed's values ( feed[e] ), but form fields are blank.在控制台中,我可以看到 JSON 提要的值 ( feed[e] ),但表单字段为空白。

What am I doing wrong?我究竟做错了什么?

Any suggestions would be much appreciated.任何建议将不胜感激。

Please use eval function.请使用 eval function。

["first", "second", "third"].forEach(e => {eval(e).value = feed[e]}); [“第一”、“第二”、“第三”].forEach(e => {eval(e).value = feed[e]});

You can try using document.getElementById to get specific DOM element您可以尝试使用document.getElementById获取特定的 DOM 元素
and then assign the value you want.然后分配你想要的值。

const feed = {
    'first': 'hello',
    'second': 'word',
    'third': '!'
};

['first', 'second', 'third'].forEach(e => {
    document.getElementById(e).value = feed[e]
});

The link below is a full demonstration.下面的链接是一个完整的演示。
https://jsfiddle.net/2x0o8d4m/1/ https://jsfiddle.net/2x0o8d4m/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM