如何检查新克隆的节点是否是javascript中的最后一个节点

How to check if newly cloned node is last node now in javascript

本文关键字:节点 是否是 最后一个 javascript 新克隆 何检查 检查      更新时间:2023-09-26

我正在尝试克隆表中的最后一行。因此,当最后一行被克隆时,新行显然成为最后一个节点。我如何使单击它时,它本身会创建一个新节点

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 ];
    });

它似乎只想将其保留在上一个节点上。我希望这是有道理的。

我建议如下,在祖先<table>级别侦听点击事件,并找出触发事件的元素:

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>

cloneNode() 不会克隆事件处理程序。因此,您应该将回调函数移动到单独的变量/命名函数,并在每次克隆它时注册它。

或者使用事件冒泡