0

我遇到的问题是当我尝试更新表 .outerHTML 中的剩余行时,以便名称属性是连续的。这是必要的,因为 .net 后端期望数组从零开始并且是连续的。

如果你有不止一行的条目,那么删除一行,当更新 outerHTML 时,DOM 值被删除,所有内容都重置为空白。有没有办法保留输入的值?它工作正常,不更新outerHTML,但不适用于后端。

https://jsfiddle.net/y2dxus1m/

    function addBenefit() {
      //gets the table and adds a new row based on length
      var tableRef = document.getElementById('benefitsField').getElementsByTagName('tbody')[0];
      var myHtmlContent = '<td><input name="Octopus.Newborns.ReceivingBenefits[' + tableRef.rows.length + '].FirstName"></td><td><input name="Octopus.Newborns.ReceivingBenefits[' + tableRef.rows.length + '].LastName"></td><td><input name="Octopus.Newborns.ReceivingBenefits[' + tableRef.rows.length + '].Amount"></td><td><input name="Octopus.Newborns.ReceivingBenefits[' + tableRef.rows.length + '].Source"></td><td><button class="btn btn-primary btn-sm" onclick="removeRow(this)">Remove</button></td>';
      var newRow = tableRef.insertRow(tableRef.rows.length);
      newRow.innerHTML = myHtmlContent;
    }

    function removeRow(a) {
      var row = a.parentNode.parentNode;
      row.parentNode.removeChild(row);
      var tableRef = document.getElementById('benefitsField').getElementsByTagName('tbody')[0];
      for (var i = 0; i < tableRef.rows.length; i++) {
        console.log(tableRef.rows[i].outerHTML)
        
        //Issue is here ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        tableRef.rows[i].outerHTML = tableRef.rows[i].outerHTML.replace(/(\[).+?(\])/g, "[" + i + "]");
        console.log(tableRef.rows[i].outerHTML)
      }
    }
<table class="deptTable" id="benefitsField">
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Weekly Benefit Amount</th>
      <th>Source</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input name="Octopus.Newborns.ReceivingBenefits[0].FirstName" /></td>
      <td><input name="Octopus.Newborns.ReceivingBenefits[0].LastName" /></td>
      <td><input name="Octopus.Newborns.ReceivingBenefits[0].Amount" /></td>
      <td><input name="Octopus.Newborns.ReceivingBenefits[0].Source" /></td>
      <td><button class="btn btn-primary btn-sm" onclick="removeRow(this)">Remove</button></td>
    </tr>
  </tbody>
</table>
<button onclick="addBenefit()">Add</button>

4

0 回答 0