就上下文而言,我链接了 Bootstrap CDN,但由于某种原因我无法在此处复制/粘贴。
当我运行此代码时,第一次提交会创建一个带有 id='masterTable'
的表格行,但每次我之后单击“提交”时,程序只会写入同一表格行,而不是创建一个新的。
我想在每次单击提交时创建一个新的表行,但我在这里被难住了。有什么想法吗?
<!DOCTYPE html>
<html>
<link>
</link>
<head>
</head>
<body>
<div class="d-flex">
<div>
<select id="ddlViewBy">
<option value="0310">XXXX-10</option>
<option value="4610" selected="selected">XXXX-10</option>
<option value="4610">XXXX-10</option>
</select>
</div>
</div>
<form>
<div class="form-group">
<label>Hand Trucks</label>
<input type="text" class="form-control" id="handtrucks" placeholder="Enter
number of Hand Trucks.">
</div>
<div>
<label>Furniture Pads</label>
<input type="text" class="form-control" id="furniture" placeholder="Enter
number of Furniture Pads.">
</div>
<button type="submit" onClick='addLocation(); return false;' id='button'
class="btn btn-primary">Submit</button>
</form>
<tbody id='masterTable'>
</tbody>
</table>
</body>
<script>
const button = document.getElementById('button');
const dropdown = document.getElementById('dropdown').value;
const htruck = document.getElementById('handtrucks').value;
const fpad = document.getElementById('furniture').value;
function addLocation() {
let masterList = document.getElementById('masterTable');
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
var handTruck = document.getElementById('handtrucks').value;
var furnPads = document.getElementById('furniture').value;
var row = document.createElement("tr");
var locationEntry = document.createElement('td');
var htEntry = document.createElement('td');
var fpEntry = document.createElement('td');
row.appendChild(locationEntry);
locationEntry.appendChild(document.createTextNode(strUser));
row.appendChild(htEntry);
htEntry.appendChild(document.createTextNode(handTruck));
row.appendChild(fpEntry);
fpEntry.appendChild(document.createTextNode(furnPads));
masterList.appendChild(locationEntry);
masterList.appendChild(htEntry);
masterList.appendChild(fpEntry);
}
</script>
</html>
最佳答案
您的问题是您要添加到 <tbody>
元素<td>
没有<tr>
。
我建议您创建一个简单的 html 代码字符串,而不是添加如此多的变量,如下所示:
let row = document.createElement('tr');
let html = '<td>' + value + '</td><td>' + value1 + '</td><td>' + value2 + '</td>';
row.innerHTML = html;
masterList.appendChild(row);
关于JavaScript - 使用 AppendChild() 将新行添加到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55199645/