Javascript 在已知 ID 的表格行之前或之后添加表格行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4515237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:45:03  来源:igfitidea点击:

Add table row before or after a table row of known ID

javascripthtmlhtml-table

提问by Perpetualcoder

In a table like this:

在这样的表中:

<table>
<!-- Insert Row of bun here -->
  <tr id="meat">
   <td>Hamburger</td>
  </tr>
<!-- Insert Row of bun here -->
</table>

function AddBefore(rowId){}
function AddAfter(rowId){}

I need to create methods without using jQuery.. I am familiar with append after and append before in jQuery.. but I am stuck with using plain js.

我需要在不使用 jQuery 的情况下创建方法.. 我熟悉 jQuery 中的 append after 和 append before .. 但我坚持使用普通 js。

回答by Gabriele Petrioli

Use

function AddBefore(rowId){
    var target = document.getElementById(rowId);
    var newElement = document.createElement('tr');
    target.parentNode.insertBefore(newElement, target);
    return newElement;
}

function AddAfter(rowId){
    var target = document.getElementById(rowId);
    var newElement = document.createElement('tr');

    target.parentNode.insertBefore(newElement, target.nextSibling );
    return newElement;
}

回答by Phrogz

You want insertBefore. Use with nextSiblingto insert after a known element.

你要insertBefore。使用 withnextSibling在已知元素之后插入。