如何将JavaScript数组绑定到动态HTML表?

时间:2015-12-28 13:17:36

标签: javascript html css

我想使用javascript添加下面创建的表中所有文本框的值,还有动作列应包含两个按钮作为编辑和删除以更新和删除文本框的值。

我创建了一个数组来保存文本框的值。 现在点击“保存”按钮,我想使用Javascript(而不是angularJS或jQuery)将这些值添加到动态HTML表中。 {

    var id = document.getElementById("id").value;
    var name = document.getElementById("name").value;
    var gender = document.getElementById("gender").value;
    var address = document.getElementById("address").value;
    var email = document.getElementById("email").value;

}

3 个答案:

答案 0 :(得分:1)

那样的东西?

function updateTable() {
  
  var values = {
    id: document.getElementById("id").value,
    name: document.getElementById("name").value,
    gender: document.getElementById("gender").value,
    address: document.getElementById("address").value,
    email: document.getElementById("email").value
  };

  var table = document.getElementById("table");

  Object.keys(values).forEach(function (key) {
    table.getElementsByClassName(key + "Row")[0]
      .getElementsByClassName("value")[0]
      .textContent = values[key];
  });
}

document.getElementById("updateTable").addEventListener("click", updateTable);
/* Purely cosmetic */
body { font-family: sans-serif; }
h1 { margin: 1em 0 0 0; font-size: 2em; }
#inputs { display: table; }
#inputs > span { display: table-row; }
#inputs label, #inputs input { display: table-cell; }
td { border: 1px solid #aaa; }
<h1>Inputs</h1>
<form id="inputs">
  <span>
	<label for="id">ID</label> <input id="id">
  </span><span>
	<label for="name">Name</label> <input id="name">
  </span><span>
    <label for="gender">Gender</label> <input id="gender">
  </span><span>
    <label for="address">Address</label> <input id="address">
  </span><span>
	<label for="email">Email</label> <input id="email">
  </span>
</form>

<h1>Table</h1>
<table id="table">
  <tr class="idRow"><td class="label">ID</td><td class="value"></td></tr>
  <tr class="nameRow"><td class="label">Name</td><td class="value"></td></tr>
  <tr class="genderRow"><td class="label">Gender</td><td class="value"></td></tr>
  <tr class="addressRow"><td class="label">Address</td><td class="value"></td></tr>
  <tr class="emailRow"><td class="label">Email</td><td class="value"></td></tr>
</table>

<button id="updateTable">Update table</button>

答案 1 :(得分:0)

试试这个:

function save() {
    var id = document.getElementById("id").value;
    var name = document.getElementById("name").value;
    var gender = document.getElementById("gender").value;
    var address = document.getElementById("address").value;
    var email = document.getElementById("email").value;
    var table = document.getElementById('table');
    var tr = document.createElement('tr');
    tr.innerHTML = '<td>' + [id,name,gender,adress,email,"save"].join('</td><td>') + '</td>';
    table.appendChild(tr);
}

答案 2 :(得分:0)

这是我的工作fiddle

{{1}}