DOM增删操作(创建删除表格)

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title></title>
<script>
//创建table
function createTable(){
var tab = document.createElement('table');
tab.border = 1;
tab.id = 'mtab';
var caption = tab.createCaption();
caption.innerHTML = 'helle';

for(var i = 0;i<5;i++){
var tr = tab.insertRow(i);
for(var j=0;j<4;j++){
var td = tr.insertCell(j);
td.innerHTML = ''+i+j;
}
}

document.getElementById('test').appendChild(tab);
}

//删除行
function deleterow(){
var tab = document.getElementById('mtab');
if(tab.rows.length > 0){
tab.deleteRow(tab.rows.length - 1);
}
}


//删除列
function deletecell(){
var tab = document.getElementById('mtab');
var row = tab.rows[tab.rows.length - 1];
if(row.cells.length > 0){
row.deleteCell(row.cells.length -1);
}
}


</script>
</head>

<body id="test">
<button value="1" onclick="createTable()">createTable</button><br />
<button value="2" onclick="deleterow()">deleterow</button><br />
<button value="3" onclick="deletecell()">deletecell</button><br />
<hr />
</body>

</html>

posted @ 2017-07-28 17:24  梁大爷  阅读(608)  评论(0编辑  收藏  举报