javascript - 从元素的 data-id 插入一组输入字段和按钮
问题描述
我目前有一个在单击按钮后显示的表单,并且保存按钮允许我将输入值保存到对象中。
如果我需要另外 9 个具有不同 data-id 的相同按钮(例如 data-id="2" 等等),而不必将函数复制到saveConditionOne中,那么编写此函数的更有效方法是什么?保存条件二,保存条件三。
const patient = {}
// Save conditions to object
function saveConditions() {
const missing = document.getElementById('missingVal').value
const movement = document.getElementById('movementVal').value
const tilt = document.getElementById('tiltVal').value
patient.one = {
missing: missing,
movement: movement,
tilt: tilt
}
console.log(patient)
}
<button data-id="1" id="showForm" class="btn">1</button>
<div id="conditionSelect">
<h5>Form</h5>
<div class="field">
<label for="">Missing Tooth</label>
<input type="text" id="missingVal">
</div>
<div class="field">
<label for="">Movement</label>
<input type="text" id="movementVal">
</div>
<div class="field">
<label for="">Tilt</label>
<input type="text" id="tiltVal">
</div>
<button id="saveCondition" onclick="saveConditions()" class="btn btn-primary">Save</button>
</div>
现在
{
"one": {
"missing": "tooth",
"movement": "1mm",
"tilt": "10deg"
}
}
预期的
{
"one": {
"missing": "tooth",
"movement": "1mm",
"tilt": "10deg"
},
"two": {
"missing": "tooth",
"movement": "1mm",
"tilt": "10deg"
},
"three": {
"missing": "tooth",
"movement": "1mm",
"tilt": "10deg"
}
}
解决方案
我不会将对象用于patient
(或至少,不会用于这部分患者信息),我会使用数组。然后您只需将数据推送到数组中:
patient.push({
missing: missing,
movement: movement,
tilt: tilt
});
...或者如果您将此作为patient
对象的属性(也许还有其他患者范围的信息):
patient.entries.push({
missing: missing,
movement: movement,
tilt: tilt
});
现场示例:
const patient = {
entries: []
}
// Save conditions to object
function saveConditions() {
const missing = document.getElementById('missingVal').value
const movement = document.getElementById('movementVal').value
const tilt = document.getElementById('tiltVal').value
patient.entries.push({
missing: missing,
movement: movement,
tilt: tilt
})
console.log(patient)
}
.as-console-wrapper {
max-height: 100% !important;
}
<button data-id="1" id="showForm" class="btn">1</button>
<div id="conditionSelect">
<h5>Form</h5>
<div class="field">
<label for="">Missing Tooth</label>
<input type="text" id="missingVal">
</div>
<div class="field">
<label for="">Movement</label>
<input type="text" id="movementVal">
</div>
<div class="field">
<label for="">Tilt</label>
<input type="text" id="tiltVal">
</div>
<button id="saveCondition" onclick="saveConditions()" class="btn btn-primary">Save</button>
</div>
推荐阅读
- codenameone - 无法再构建:OutOfMemoryError Java 堆空间
- linkedin - v2 API 权限 [案例:190112-003775]
- javascript - 在 Typescript 中,实例化对象的方法可以在 map() 使用时访问该对象的属性吗?
- jquery - jQuery getScript 不工作,或者我用错了
- bash - bash中`>|`的含义?
- c - 停止和启动任务
- collections - 如何在 Kotlin 中使用唯一的增量键对值进行分组?
- excel - 如何引用许多填充文本的单元格并拥有所有格式副本?
- ethereum - Solidity 源文件需要不同的编译器版本
- r - 在 x 轴下标注