使用Javascript动态增加,删除表格(使用W3C对象模型)
<
html
>
<
meta
http-equiv
="Content-Type"
content
="text/html; charset=utf-8"
/>
<
head
>


<
script
language
="javascript">

function deleteRow(index){
var tableObj=document.getElementById("mainBody");
var rowObj=document.getElementById('row'+index);
tableObj.removeChild(rowObj);
}
function addRow(){
var tableObj=document.getElementById("mytable");
var tableBodyObj=document.getElementById("mainBody");
var newRowObj=document.createElement("tr");
newRowObj.id="row"+(tableObj.rows.length-1);
var newColName=document.createElement("td");
var newColAge=document.createElement("td");
var newColButton=document.createElement("td");
newColName.innerHTML=document.getElementById("newName").value;
newColAge.innerHTML=document.getElementById("newAge").value;
newColButton.innerHTML='<input type="button" value="删除" onclick="deleteRow('+(tableObj.rows.length-1)+')">';
newRowObj.appendChild(newColName);
newRowObj.appendChild(newColAge);
newRowObj.appendChild(newColButton);
tableBodyObj.appendChild(newRowObj);
}
</
script
>
</
head
>

<
body
>
<
table
width
="100%"
id
="mytable"
border
="0"
cellspacing
="0"
cellpadding
="0"
>
<
tbody
id
="mainBody"
>
<
tr
>
<
td
>
姓名
</
td
>
<
td
>
年龄
</
td
>
<
td
>
操作
</
td
>
</
tr
>
<
tr
id
="row0"
>
<
td
>
gaoxiang
</
td
>
<
td
>
28
</
td
>
<
td
><
input
type
="button"
onclick
="deleteRow(0)"
value
="删除"
/></
td
>
</
tr
>
<
tr
id
="row1"
>
<
td
>
gaoxiang
</
td
>
<
td
>
28
</
td
>
<
td
><
input
type
="button"
onclick
="deleteRow(1)"
value
="删除"
/></
td
>
</
tr
>
</
tbody
>
</
table
>

<
input
type
="text"
name
="name"
id
="newName"
/>
<
input
type
="text"
name
="age"
id
="newAge"
/>
<
input
type
="button"
onclick
="addRow();"
value
="新增"
/>
</
body
>
</
html
>
本文介绍了一种使用JavaScript和W3C对象模型实现表格动态添加和删除的方法。通过获取表格元素,可以创建新的行和列,并将其添加到表格中;同时也可以通过指定行的ID来删除指定的行。
733

被折叠的 条评论
为什么被折叠?



