首页 > 解决方案 > 从元素的 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"
  }
}

标签: javascriptjqueryhtml

解决方案


我不会将对象用于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>


推荐阅读