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
Add table row before or after a table row of known ID
提问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 nextSibling
to insert after a known element.
你要insertBefore
。使用 withnextSibling
在已知元素之后插入。