方法(1)此方法不能在制定的位置添加
<script language="javascript">
- var table = document.getElementById("table_id");
- var tr = table.insertRow();
- for(var i=0; i<4; i++){
- var td = tr.insertCell(i);
- td.innerText = i;
- }
- </script>
- <table border=1 id="table_id">
- </table>
方法(2)实现
function
onAddTR(trIndex)
{
var
tb = document.getElementById(
"tb1"
);
var
newTr = tb.insertRow(trIndex);
//添加新行,trIndex就是要添加的位置
var
newTd1 = newTr.insertCell();
newTd1.innerHTML =
"这是新行,位置:"
+ trIndex;
var
newTd2 = newTr.insertCell();
newTd2.innerHTML =
"这是新行,位置:"
+ trIndex;
}
方法(3)jQuery实现
<
table
style
=
"width: 100%;"
id
=
"tb1"
>
<
tr
onclick
=
"onAddTR(this)"
>
<
td
>1</
td
>
<
td
>2</
td
>
</
tr
>
<
tr
onclick
=
"onAddTR(this)"
>
<
td
>3</
td
>
<
td
>4</
td
>
</
tr
>
</
table
>
<
script
type
=
"text/javascript"
>
function onAddTR(trObj)
{
$(trObj).after("<
tr
onclick
=
'onAddTR(this)'
><
td
>这是新行</
td
><
td
></
td
><
tr
/>");
}
</
script
>
方法(4)dom实现在制定的位置前插入tr
原文:
<table>
<tr id="insertSpareEpt">
<td colspan="24" align="right"><input type="button" value="添加" οnclick="insertSpareEpt()"/></td>
</tr>
</table>
脚本:
<script type="text/javascript">
function insertSpareEpt(){
var insertSpareEpt=document.getElementById("insertSpareEpt");
var newChild=document.createElement("tr");
newChild.innerHTML=" <td colspan='2'><%=j%></td> <td colspan='8'><input type='text' name='spareEpt<%=j%>'> </td><td colspan='7'><input type='text' name='spareEptStyle<%=j%>'></td><td colspan='2'><input type='text' name='spareEptUnit<%=j%>' size='14' /></td><td colspan='3'><input type='text' name='spareEptNum<%=j %>' size='14'/></td> <td colspan='2' ><input type='button' value='删除' οnclick='deleteTrShow()'/></td>";
//var newChild2=document.createElement("tr");
//newChild.innerHTML="<td colspan='24' align='left'><input type='button' value='删除'/></td>";
insertSpareEpt.parentNode.insertBefore(newChild,insertSpareEpt);
}