gpt4 book ai didi

javascript - 删除父节点时保存子节点

转载 作者:行者123 更新时间:2023-11-28 00:05:41 25 4
gpt4 key购买 nike

我尝试制作一个工具栏,单击它后将其附加到表格行。在下面的代码中,工具栏的功能仅限于删除一行以使事情更清晰。这个想法是在不使用工具栏以及要删除其行时将工具栏“停放”到工具DIV(隐藏在真实应用程序中)中。问题是删除表行后工具栏消失。这很奇怪,因为首先它被成功附加到它的“home”(工具 DIV),然后从必须删除的行中删除。所以工具栏应该是安全的。然而,当 onclick 事件结束时,工具栏就消失了。观看下面的代码片段,了解警报框之前和之后的情况。到底是怎么回事?

function addToolbar(cell) {
cell.appendChild(document.getElementById('toolbar'));
}

function deleteRow(rownum) {
document.getElementById('tools').appendChild(document.getElementById('toolbar'));
document.getElementById('mytable').deleteRow(rownum);
alert('Now the toolbar is parked back to the "tools" DIV as it is suppossed to be. After you click OK the deleteRow() function returns and the toolbar will be deleted. Why?');
}
#tools, #mytable, #toolbar {
border-style: solid;
border-color: black;
border-width: 1px;
}
<div id='tools'>
TOOLS DIV. Here is a place for parking the toolbar when not used.
Unfortunatelly it disappears
<div id='toolbar' onclick='deleteRow(this.parentNode.rowIndex)'>
Delete this row
</div>
</div>
<br>
Click on the table rows below to append the "toolbar".
<table id='mytable'>
<tr onclick='addToolbar(this);'>
<td>
First row
</td>
<td>
<!--a place for the toolbar-->
</td>
</tr>
<tr onclick='addToolbar(this)'>
<td>
Second row
</td>
<td>
<!--a place for the toolbar-->
</td>
</tr>
</table>

最佳答案

发生的情况是,针对工具栏的单击事件向上冒泡到父节点(在本例中为 tr 行),触发其 onclick 处理程序。

您可以通过将事件对象传递给 deleteRow 函数并调用其 stopPropagation 方法来阻止此机制。

function addToolbar(cell) {
cell.appendChild(document.getElementById('toolbar'));
}

function deleteRow(event, rownum) {
document.getElementById('tools').appendChild(document.getElementById('toolbar'));
document.getElementById('mytable').deleteRow(rownum);
alert('Now the toolbar is parked back to the "tools" DIV as it is suppossed to be. After you click OK the deleteRow() function returns and the toolbar will be deleted. Why?');

event.stopPropagation();
}
#tools, #mytable, #toolbar {
border-style: solid;
border-color: black;
border-width: 1px;
}
<div id='tools'>
TOOLS DIV. Here is a place for parking the toolbar when not used.
Unfortunatelly it disappears
<div id='toolbar' onclick='deleteRow(event, this.parentNode.rowIndex)'>
Delete this row
</div>
</div>
<br>
Click on the table rows below to append the "toolbar".
<table id='mytable'>
<tr onclick='addToolbar(this);'>
<td>
First row
</td>
<td>
<!--a place for the toolbar-->
</td>
</tr>
<tr onclick='addToolbar(this)'>
<td>
Second row
</td>
<td>
<!--a place for the toolbar-->
</td>
</tr>
</table>

我不完全确定 event 对象在所有当前浏览器的 HTML 声明中都可用,因此我建议以编程方式附加事件监听器。

关于javascript - 删除父节点时保存子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31361542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com