I am trying to clone the last row in a table. So when the last row is cloned, the new row obviously becomes the last node. How do I made it that when that is clicked, it, itself creates a new node
window.onload = function() {
var table = document.getElementById("nodeTable");
var lastRow = table.rows[ table.rows.length - 1 ];
lastRow.addEventListener('click', function() {
var clone = lastRow.cloneNode(true);
// var row = table.insertRow(-1);
table.appendChild(clone);
// now set the newly cloned node as the last node
lastRow = table.rows[ table.rows.length - 1 ];
});
It seems to want to just leave it at the previous node. I hope this makes sense.
cloneNode() does not clone event handlers . So you should move the callback function to a separate variable/named function and register it every time you clone it.
Alternatively use event bubbling
I'd suggest the following, listening for click-events at the level of the ancestor <table>
and working out what element fired the event:
var table = document.getElementById('nodeTable');
// binding the event-listener to the <table>:
table.addEventListener('click', function(e) {
// this is the <table> itself,
// this.rows is the collection of <tr> descendants:
var rows = this.rows,
// e.target is the clicked element:
current = e.target,
body = document.body,
// getting the last row of the table:
lastRow = rows[rows.length - 1];
// while the clicked element does not have the (lower-cased) tagName of 'tr',
// and it's not the 'body' (just for safety):
while (current.tagName.toLowerCase() !== 'tr' && current !== body) {
// we update current to be its own parentNode and go again
current = current.parentNode;
}
// if the current-element is the lastRow:
if (current === lastRow) {
// we append the cloned row to the parentNode of the
// lastRow (which will be a <tbody>, not the <table>:
lastRow.parentNode.appendChild(lastRow.cloneNode(true));
}
});
var table = document.getElementById('nodeTable'); table.addEventListener('click', function(e) { var rows = this.rows, current = e.target, body = document.body, lastRow = rows[rows.length - 1]; while (current.tagName.toLowerCase() !== 'tr' && current !== body) { current = current.parentNode; } if (current === lastRow) { lastRow.parentNode.appendChild(lastRow.cloneNode(true)); } });
table { counter-reset: rowCount; } td { border: 1px solid #000; width: 3em; height: 2em; } td::before { content: counter(rowCount); counter-increment: rowCount; }
<table id="nodeTable"> <tbody> <tr> <td></td> </tr> </tbody> </table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.