javascript - 从 JavaScript 对象属性创建表单
问题描述
我有一个运行 JSON 数据的 Web 应用程序,我提取了一部分并最终得到一个具有一些属性的对象:
var formProps = {
Name: "Some Name value",
Age: "18",
AnotherField: "Some other value"
}
我正在尝试找到一种从属性创建表单的有效方法。
<div class="formitem">
<label>Some Name Value</label>
<input type="text" name="AnotherField" value="Some other value"/>
</div>
我无法决定是否应该生成 HTML 并将其转储到页面上已经存在的另一个 div 中,或者是否应该通过 JS 创建新的 DOM 元素...
解决方案
如果你希望它是动态的,你别无选择,只能从 JavaScript 创建新的 DOM 元素。
一种方法是使用 HTML 模板定义表单项结构,这将允许您在 HTML 中定义大部分结构。然后,您可以为对象中的每个属性在页面中克隆、自定义和附加此模板。
const formProps = {
Name: "Some Name value",
Age: "18",
AnotherField: "Some other value"
}
function createField(prop, value) {
const tpl = document.querySelector('#formitem-tpl');
const clone = document.importNode(tpl.content, true);
clone.querySelector('label').innerHTML = prop;
const input = clone.querySelector('input');
input.value = value;
input.name = prop;
return clone;
}
const form = document.querySelector('#form');
for (let [key, val] of Object.entries(formProps)) {
form.appendChild(createField(key, val));
}
<template id="formitem-tpl">
<div class="formitem">
<label></label>
<input type="text" name="" value=""/>
</div>
</template>
<div id="form">
</div>
推荐阅读
- python - Selenium Webdriver Python - 如何在随机更改的 JS 按钮中单击正确的数字?
- python - 如何在字典类型上使用 str.format()?
- python-3.x - 从 API 提取数据时的等待屏幕
- node.js - 处理快速管道中的错误
- apache-spark - spark如何仅加载目录中的部分文件?
- python - colab中的torchtext ImportError
- laravel - 根据另一个字段的 Laravel 验证最大数量(来自 period_starts 的 +2
- python - 使用 Tkinter 手动注释
- java - 将事件发布到 microsoft graph 时出现错误 (java.lang.NoSuchMethodError: okhttp3.Request$Builder.tag)
- bash - 我们可以在 shell 脚本(Bash)中使用 lldb 吗?