【问题标题】:Insert html form data into the end of a table <tr> using vanilla Javascript使用 vanilla Javascript 将 html 表单数据插入到表 <tr> 的末尾
【发布时间】:2019-10-04 10:54:43
【问题描述】:

我创建了一个触发 onSubmit 的 javascript 函数,它应该获取输入数据并将其添加到同一页面上表的新行中。

我在控制台中没有看到任何错误。但是数据并没有进入表格。

以下是我的第一次尝试:

    function addRow() {
      // Get a reference to the table
      let tableRef = document.getElementById('Job-table');
       console.log(tableRef);
      // Insert a row at the end of the table
      let newRow = tableRef.insertRow(-1);

      // Insert a cell in the row at index 0
      let newCellJobName = newRow.insertCell(0);
      let newCellJobDate = newRow.insertCell(1);
      let newCellJobHost = newRow.insertCell(2);

      // Below I is a test with a static string
      //let newJobName = document.createTextNode("TEST 1");
      //let newJobDate = document.createTextNode("TEST 2");
      //let newJobHost = document.createTextNode("TEST 3");

  // Append a text node to the cell
  let newJobName = document.createTextNode(document.getElementById("JobName").value);
  let newJobDate = document.createTextNode(document.getElementById("JobDate").value);
  let newJobHost = document.createTextNode(document.getElementById("JobHost").value);

      newCellJobName.appendChild(newJobName);
      newCellJobDate.appendChild(newJobDate);
      newCellJobHost.appendChild(newJobHost);
    }

这是我的表格的 HTML:

<table id="Job-table">
<tbody>
<tr><td>Test Job</td><td>12/05/2012</td><td>Mike Smith</td></tr>
<tr><td>Test Job</td><td>12/06/2012</td><td>Mike Smith</td></tr>
<tr><td>Test Job</td><td>12/07/2012</td><td>Mike Smith</td></tr>
</tbody>
</table>

我知道表单输入 .value 存在问题,但我也尝试传递静态字符串,但没有运气。

【问题讨论】:

  • 作为旁注,我不明白非常冗长的文本节点创建的好处。 newCellJobName.textContent = document.getElementById("JobName").value 要短得多。
  • 如果我们不知道 insertRownewRow 是/做什么,那么应该如何帮助您?
  • @connexo 我添加了要添加 insertRow 和 newRow 的 HTML 表。我可以添加提交添加到表单中的值的 HTML 表单。

标签: javascript forms html-table


【解决方案1】:

您可以使用内部 html 简单地添加它:

var inner = document.getElementById("Job-table").innerHTML;
document.getElementById("Job-table").innerHTML = inner + "<tr>...</tr>";

【讨论】:

    【解决方案2】:

    您正在使用未声明的变量。换行就行了

    newCellJobHost.appendChild(newJobAssigned);
    

    newCellJobHost.appendChild(newJobHost);
    

    【讨论】:

    • 很抱歉错过了查找和替换。我使用假名是因为真名不适合使用。
    • 你有笨蛋吗?您编写的代码确实有效。但是,它可以进行优化。
    猜你喜欢
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 2020-09-03
    • 2017-05-14
    相关资源
    最近更新 更多