如何检查新克隆的节点是否是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 ];
});
它似乎只想将其保留在上一个节点上。我希望这是有道理的。
我建议如下,在祖先<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() 不会克隆事件处理程序。因此,您应该将回调函数移动到单独的变量/命名函数,并在每次克隆它时注册它。
或者使用事件冒泡
相关文章:
- 节点是否需要模块传递带有方括号的arg?这是个错误吗
- node.js测试事件是否是在不使用超时的情况下使用sinon.js发出的
- 确定var是否是javascript中的elementFinder对象的方法是什么
- 检查对象是否是mongo游标
- 如何检查DOM节点是否继承自构造函数
- 是否可以测试javascript函数是否是构造函数
- 检查请求的用户是否是django中的所有者
- 角度 2 :检查路由名称是否是当前名称
- 我怎么知道日期是否是星期六
- 从不断变化的动作创建者那里获取商店数据是否是一种常见的做法
- 如何确定父节点是否有子节点
- 力导向图-如果节点同时是源和目标,则定义节点的颜色
- 在node.js/ssocket.io中,如何判断对象是否是套接字的实例
- 在jQuery中,如何测试一个元素是否是同一类的多个元素中的第一个
- 是否有跨浏览器和跨框架的方法来检查对象是否是HTML元素
- 如何检查 DOM 节点是否是“html”节点
- 如何检查新克隆的节点是否是javascript中的最后一个节点
- 使用 JQuery 检查所选文本是否是较大节点的一部分
- 如何知道所选节点是否是树中的一片叶子?(ExtJS 4)
- 元素属性是否是节点