我是 Html 和 javascript 新手。我想在单击按钮时使用表中的输入字段创建动态行,即用户给出的行数。在我的代码中,动态创建了行,但它没有附加上一个。它是新鲜创建的。但是,如果表已经创建,我想追加行。
这是我的代码:
function createTable() {
var a;
a = document.getElementById('tb1').value;
if (a == "") {
alert("Please enter some numeric value");
} else {
var rows = "<th>Item Name</th><th>Quantity</th><th>QuantityType</th><th>Amount</th>";
for (var i = 0; i < a; i++) {
rows += "<tr><td><input type='text' name='" + "name".concat(i+1) + "'></td><td><input type='text' name='" + "quantity".concat(i+1) + "'></td><td><input type='text' name='" + "qtype".concat(i+1) + "'></td><td id='amt'><input type='text' id='sum' onkeyup='myfunction(this.value);' name='" + "total".concat(i+1) + "'></td></tr>";
}
document.getElementById("table").innerHTML = rows;
}
}
div {
background: red;
margin: 5px;
}
table {
border: 2px solid black;
}
td {
padding: 10px;
border: 1px solid lightgrey;
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="text" id="tb1"/>
<button type="button" onclick='createTable()'>Click Me!</button>
<table id="table" class="order-table table" name="table1" required>
</table>
</body>
</html>
请任何人帮忙!
提前致谢..
Use Element.appendChild
代替innerHTML
-
Element.firstChild
将返回first-child
的元素。
-
querySelectorAll
将返回NodeList
根据指定的选择器。
-
Element.appendChild
将追加新的Node
元素中的内容而不影响元素中的现有内容。
function createTable() {
var a = document.getElementById('tb1').value;
if (a == "") {
alert("Please enter some numeric value");
} else {
var th = document.querySelectorAll('#table th');//To check whether `TD` is appended in table or not!
if (!th.length) {
//If not appended, then append TD in table
var rows = "<th>Item Name</th><th>Quantity</th><th>QuantityType</th><th>Amount</th>";
var table = document.createElement('table');
table.innerHTML = rows;
document.getElementById("table").appendChild(table.firstChild);
}
for (var i = 0; i < a; i++) {
var elems = '';
elems += "<tr><td><input type='text' name='" + "name".concat(i + 1) + "'></td><td><input type='text' name='" + "quantity".concat(i + 1) + "'></td><td><input type='text' name='" + "qtype".concat(i + 1) + "'></td><td id='amt'><input type='text' id='sum' onkeyup='myfunction(this.value);' name='" + "total".concat(i + 1) + "'></td></tr>";
var table = document.createElement('table');
table.innerHTML = elems;
document.getElementById("table").appendChild(table.firstChild);
}
}
}
div {
background: red;
margin: 5px;
}
table {
border: 2px solid black;
}
td {
padding: 10px;
border: 1px solid lightgrey;
}
<input type="text" id="tb1" />
<button type="button" onclick='createTable()'>Click Me!</button>
<table id="table" class="order-table table" name="table1" required>
</table>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)