练习:table添加删除一行;
添加子元素用:appendChild; 为元素添加内容用:object.innerHTML,oTd.innerHTML='<a href="javascript:;">删除</a>'
删除元素用:父节点.removeChild(子节点)
添加,删除都是操作tbody里面的tr;
添加行的序号:用oTab.tBodies[0].rows.length+1数组序号加1来作为行的序号;每加一行加1.为了使删除某一行后,序号依旧按元顺序增加,所以用一个变量id来储存当前序号,那么即便删除一行后,序号还是不变,当再加一行时,序号顺延加1;代码:
var id=oTab.tBodies[0].rows.length+1;
var oTr=document.createElement('tr'); var oTd=document.createElement('td'); oTd.innerHTML=id++; oTr.appendChild(oTd);
<body> 姓名: <input id='name'type='text'/> <input id='age' type='text'/> <input id='btn1' type='button' value='添加'/> <table id='tab1' border='1px solid black' width='280px'> <thead> <td>序号</td> <td>姓名</td> <td>年龄</td> <td>操作</td> </thead> <tbody> <tr> <td>1</td> <td>刘一</td> <td>23</td> <td></td> </tr> <tr> <td>2</td> <td>浩二</td> <td>24</td> <td></td> </tr> <tr> <td>3</td> <td>张三</td> <td>26</td> <td></td> </tr> <tr> <td>4</td> <td>麻四</td> <td>23</td> <td></td> </tr> <tr> <td>5</td> <td>王五</td> <td>29</td> <td></td> </tr> <tr> <td>6</td> <td>张四</td> <td>27</td> <td></td> </tr> </tbody> </table> </body>
<script> window.onload=function(){ var oTab=document.getElementById('tab1'); var oName=document.getElementById('name'); var oAge=document.getElementById('age'); var oBtn=document.getElementById('btn1'); var id=oTab.tBodies[0].rows.length+1; oBtn.onclick=function(){ var oTr=document.createElement('tr'); var oTd=document.createElement('td'); oTd.innerHTML=id++; oTr.appendChild(oTd); var oTd=document.createElement('td'); oTd.innerHTML=oName.value; oTr.appendChild(oTd); var oTd=document.createElement('td'); oTd.innerHTML=oAge.value; oTr.appendChild(oTd); var oTd=document.createElement('td'); //var oA=document.createElement('a'); //oA.innerHTML='删除'; //oA.href='javascript:;'; //oTd.appendChild(oA); oTd.innerHTML='<a href="javascript:;">删除</a>' oTr.appendChild(oTd); oTd.getElementsByTagName('a')[0].onclick=function(){ oTab.tBodies[0].removeChild(this.parentNode.parentNode); } oTab.tBodies[0].appendChild(oTr); } } </script>