我试图在克隆表的顶部放置一条水平线,而不添加任何新的html标签,例如<p>
,<div>
或任何类似标签。我不知道如何实现。
我也尝试过在检测到style.border
事件时添加一个click
,但看起来只有在加载id
页面后才能获得html
。可能我在这里做错了。
这是我的代码:
function newtable(id) {
var table = document.getElementById(id).lastChild;
var tr = table.lastChild;
var lastId = Number(tr.getAttribute('id').split('_')[1]);
var trClone = tr.cloneNode(true);
trClone.setAttribute('id', id + '_' + (lastId + 1));
trClone.lastChild.childNodes[0].setAttribute('onclick', 'remove(' + id + ',' + (lastId + 1) + ')');
table.appendChild(trClone);
var b = document.getElementById(id).style.borderBottomColor = "red"; //i try to add horizontal line here every time this function is trigger.
}
<table>
<tbody>
<tr>
<td>
<table id="1">
<tr>
<td>
<span>Name</span> <input type="text" value="Peterson" />
</td>
<td>
<span>Country</span><input type="text" value="England" />
</td>
<td>
<span>Email</span><input type="text" value="Peterson@gmail.com" />
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<input type="button" value="Add" onclick="newtable(10)" />
</td>
</tr>
</tbody>
</table>
每次单击添加按钮将克隆表并在新克隆表顶部绘制水平线。
答案 0 :(得分:2)
我试图修复一些小错误:
lastChild()
替换为table.rows[lastRowIndex]
,以获得表的最后一个元素。newId
以更新ID。mainTable.insertRow(mainTable.rows.length);
在<tbody>
的{{1}}中添加一行。main-tbl
元素添加了.adder
类。<tr>
类:.adder
这是一个有效的示例:
tr:not(.adder):not(:first-child):not(:last-child)
let mainTable = document.getElementById('main-tbl');
function addNewRow(id) {
let table = document.getElementById('inner-tbl');
let lastRowIndex = table.rows.length - 1;
let trOrigin = table.rows[lastRowIndex];
let lastId = Number(trOrigin.getAttribute('id').split('_')[1]);
let newId = 'item_' + (lastId + 1);
trOrigin.setAttribute('id', newId);
let trClone = trOrigin.cloneNode(true);
let lastCellIndex = trClone.cells.length - 1;
// Insert a row in the table at the last row
let newRow = mainTable.insertRow(mainTable.rows.length);
newRow.setAttribute('id', newId);
newRow.innerHTML = trClone.innerHTML;
newRow.cells[lastCellIndex].setAttribute('onclick', 'remove(' + id + ',' + (lastId + 1) + ')');
}
body {
overflow-y: scroll;
}
#main-tbl>tbody>tr:not(.adder):not(:first-child):not(:last-child)>td {
// border-top: 1px solid #000;
background-color: red;
}
#main-tbl {
width: 100%;
table-layout: fixed;
overflow-wrap: break-word;
}