>我制作了一个按钮将单元格作为列添加到一组行中,但是当我尝试单击该按钮以添加整列时,它会将td
元素作为文本插入
这是代码
add_col.on('click',function() {
var table = $('#table_data'), //get the table
rowsNum = $('#table_data tr').length // get number of rows
cellsNum = document.getElementById('table_data').rows[0].cells.length
for(x = 0;x < rowsNum; x++){
//document.getElementById('table_data').rows[x].insertCell(cellsNum)
document.getElementById('table_data').rows[x].append('<td></td>')
}
})
[https://jsfiddle.net/georgesteven1/3kpg6e8c/9/][1]
如果使用 Jquery,则可以浏览表 tr 并添加新的 td。
add_col.on('click',function() {
$('#table_data tbody tr').each(function( index ) {
$('<td />').appendto($(this));
});
});
查看addColumn()
函数。
这很简单。
- 选择表中的所有行。
- 为每行创建一个
<td>
。 - 将这些 TD 附加到行中。
PS:您可以决定为函数提供更多参数,例如列的标题和默认值。现在我只选择了表的 ID 作为参数,因此您至少可以在表中重用它。 PS2:我从按钮上的onclick事件触发了该功能。
function addColumn( tableId ) {
let tableRows = document.querySelectorAll( `#${tableId} tr` );
tableRows.forEach( row => {
let td = document.createElement('td');
row.appendChild(td);
});
}
.add{position: fixed;top:10px}
table{
margin: 30px auto;
}
table th,td{
padding:10px;
border-bottom: 1px solid #ddd;
border-right:1px solid #ddd;
text-align: center;
}
input{
width:100px;
}
<div class="add">
<button id="add-btn">Add Row</button>
<button id="addCol-btn" onclick="addColumn('table_data')">Add Column</button>
</div>
<table id="table_data">
<th>Name</th>
<th>Color</th>
<th>Price</th>
<tr>
<td>Alex</td>
<td>Red</td>
<td>150</td>
</tr>
<tr>
<td>Max</td>
<td>Blue</td>
<td>300</td>
</tr>
<tr>
<td>Mike</td>
<td>Black</td>
<td>700</td>
</tr>
</table>
您可以按如下方式简化函数:
add_col.on('click',function() {
$("#table_data tr").each(function(i) {
if( i > 0 ) {
$(this).append('<td><input type="text" /></td>')
}
});
});
这是更新的小提琴
我已经更新了你的小提琴。 当您选择使用Document.getElementbyid时,您需要在对象中将其转换为使用追加功能。
var td=$("<td/>");
var rowObj=$(document.getElementById('table_data').rows[x])
rowObj.append(td);
在此处查看考试
我能够用jQuery做到这一点,试试这个:
// add column
add_col.on('click',function() {
var table = $('#table_data'), //get the table
rowsNum = $('#table_data tr').length // get number of rows
$("#table_data tr").each((index) => {
$("#table_data tr").eq(index).append('<td>!</td>')
})
})