删除父节点时保存子项

时间:2015-07-11 20:32:17

标签: javascript dom

我尝试制作一个工具栏,点击它后附加到表格行。在下面的代码中,工具栏的功能仅限于删除一行以使事情更清晰。这个想法是将工具栏“停放”到工具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>

1 个答案:

答案 0 :(得分:1)

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

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

&#13;
&#13;
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();
}
&#13;
#tools, #mytable, #toolbar {
  border-style: solid;
  border-color: black;
  border-width: 1px;
}
&#13;
<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>
&#13;
&#13;
&#13;

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