有很多类似的问题,但是我能找到的每个问题都在使用我想减轻的jQuery。插入行的内容将动态创建。我坏了的方法:
function addRow() {
let newRow = '<tr><td>Boo</td><td>✔</td><td></td><td>✔</td></tr>';
document.getElementById('new').insertBefore(newRow);
}
body {
padding: 50px;
font-family: sans-serif;
}
table, th, td {
border: 1px solid #000;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
th {
text-transform: capitalize;
}
#new {
text-align: center;
font-weight: bold;
}
#new:hover {
cursor: pointer;
background-color: grey;
color: #fff;
}
<table>
<tbody>
<tr>
<th>title</th>
<th>multiple</th>
<th>required</th>
<th>special</th>
</tr>
<tr>
<td>Bar</td>
<td>✔</td>
<td>✔</td>
<td>✔</td>
</tr>
<tr>
<td>Foo</td>
<td>✔</td>
<td></td>
<td>✔</td>
</tr>
<tr>
<td id="new" colspan="6" onClick="addRow">ADD NEW SETTING</td>
</tr>
</tbody>
</table>
如果您认为应该以不同的方式进行操作,请随意优化代码。
答案 0 :(得分:3)
您可以使用insertAdjacentHTML
:
function addRow() {
let newRow = '<tr><td>Boo</td><td>✔</td><td></td><td>✔</td></tr>';
document.getElementById('new').parentElement.insertAdjacentHTML('beforebegin', newRow)
}
body {padding: 50px; font-family: sans-serif;}
table, th, td {border: 1px solid #000; border-collapse: collapse;}
th, td {padding: 15px;}
th {text-transform: capitalize;}
#new {text-align: center; font-weight: bold;}
#new:hover {cursor: pointer; background-color: grey; color: #fff;}
<table>
<tbody>
<tr>
<th>title</th><th>multiple</th><th>required</th><th>special</th>
</tr>
<tr>
<td>Bar</td><td>✔</td><td>✔</td><td>✔</td>
</tr>
<tr>
<td>Foo</td><td>✔</td><td></td><td>✔</td>
</tr>
<tr>
<td id="new" colspan="6" onClick="addRow()">ADD NEW SETTING</td>
</tr>
</tbody>
</table>
答案 1 :(得分:0)
正如@Teemu所建议的,使用HTMLTable Interface而不是使用HTML字符串是更好的实践:
function addRow() {
const table = document.getElementById('dictionary');
let text = ['Boo', undefined, '✔', '✔'];
let row = table.insertRow(table.rows.length-1);
for (let i = 0; i < table.rows[0].cells.length; i++) {
row.insertCell(-1).textContent = text[i] || '';
}
}
body {padding: 50px; font-family: sans-serif;}
table, th, td {border: 1px solid #000; border-collapse: collapse;}
th, td {padding: 15px;}
th {text-transform: capitalize;}
#new {text-align: center; font-weight: bold;}
#new:hover {cursor: pointer; background-color: grey; color: #fff;}
<table>
<tbody id="dictionary">
<tr>
<th>title</th><th>multiple</th><th>required</th><th>special</th>
</tr>
<tr>
<td>Bar</td><td>✔</td><td>✔</td><td>✔</td>
</tr>
<tr>
<td>Foo</td><td>✔</td><td></td><td>✔</td>
</tr>
<tr>
<td id="new" colspan="6" onClick="addRow()">ADD NEW SETTING</td>
</tr>
</tbody>
</table>
如果快速且肮脏的项目适合您,请参见以下答案-效果很好。