在没有jquery的索引处插入HTML表行克隆

时间:2017-09-06 17:51:08

标签: javascript html

我试图在addmorebutton td行的索引处插入一行。

第一次尝试确实在所需的索引处添加了一行,但不像我预期的那样,只是作为空格与实际添加有界行列框。

如何在点击的td索引处插入一个新行,该行是空的并且确实是表格的一部分?

function deleteRow(row) {
  var i = row.parentNode.parentNode.rowIndex;
  document.getElementById('Table').deleteRow(i);
}


function addRow() {
  var i = row.parentNode.parentNode.rowIndex;
  document.getElementByID('Table').insertRow(i);
}
turkSetAssignmentID();
<script type='text/javascript' src='https://s3.amazonaws.com/mturk-public/externalHIT_v1.js'></script>
<form name='mturk_form' method='post' id='mturk_form' action='https://www.mturk.com/mturk/externalSubmit'>
  <input type='hidden' value='' name='assignmentId' id='assignmentId' />

  <h1>This is a test</h1>

  <div id="tablediv">
    <input type="button" id="addbutton" value="Add Index" /><br/><br/>
    <table id="Table" border="1">
      <tr>
        <td>Index</td>
        <td>Measured Depth</td>
        <td>Inclination</td>
        <td>Azimuth</td>
        <td>Delete?</td>
        <td>Add Row?</td>
      </tr>
      <tr>
        <td>1</td>
        <td><input size=25 type="text" id="Measured Depth" contenteditable='true'></td>
        <td><input size=25 type="text" id="Inclination" contenteditable='true'></td>
        <td><input size=25 type="text" id="Azimuth" contenteditable='true'></td>
        <td><input type="button" id="delbutton" value="Delete" onclick="deleteRow(this)" /></td>
        <td><input type="button" id="addmorebutton" value="Add More Indexs" onclick="addRow.apply(this)" /></td>
      </tr>
    </table>
  </div>

  <p><input type='submit' id='submitButton' value='Submit' /></p>
</form>

1 个答案:

答案 0 :(得分:0)

您可以尝试将相应的单元格添加到新行,将行保存在varappendChild()功能上。像这样:

&#13;
&#13;
function addRow(row) {
      var i = row.parentNode.parentNode.rowIndex + 1;
      var nextRow = document.getElementById('Table').insertRow(i);

      // Start iterating over all the cells on the row
      var cell = nextRow.insertCell(0);
      cell.appendChild(document.createTextNode(i));
      cell = nextRow.insertCell();
      cell = nextRow.insertCell();
      cell = nextRow.insertCell();
      cell = nextRow.insertCell();
      cell = nextRow.insertCell();
      input = document.createElement("Input");
      input.type = "button";
      input.setAttribute("onclick", "addRow(this)");
      input.value = "Add More Indexs"
      cell.appendChild(input);
    }
&#13;
&#13;
&#13;

当然,在每个单元格上附加相应的输入。 那么也许你想添加一个函数来增加新的行的索引号...

此外,我将原始按钮上的onclick值更改为addRow(this)