簡體   English   中英

如何在javascript中現在檢查新克隆的節點是否是最后一個節點

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

我正在嘗試克隆表的最后一行。 因此,當克隆最后一行時,新行顯然成為最后一個節點。 我如何做到這一點,當它被單擊時,它本身會創建一個新節點

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

似乎只想將其保留在上一個節點。 我希望這是有道理的。

cloneNode()不克隆事件處理程序 因此,您應該將回調函數移至單獨的變量/命名函數,並在每次克隆時進行注冊。

或者使用事件冒泡

我建議采取以下措施,在祖先<table>級別偵聽click-events,並找出觸發該事件的元素:

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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM