首页 > 编程语言 > 详细

JavaScript操作DOM(动态表格处理)

时间:2017-10-25 22:33:04      阅读:170      评论:0      收藏:0      [点我收藏+]
<html>
	<title>动态处理表格数据</title>
    <head>
    	<script type="text/javascript">
          function clearForm(){
              document.getElementById("deptno").value="";
              document.getElementById("dname").value="";
          }
          window.onload=function(){
             document.getElementById("addBtn").addEventListener("click",onloadData,false);
          }

          function onloadData(){
          	var deptno=document.getElementById("deptno").value;
          	var dname=document.getElementById("dname").value;
          	addRow(deptno,dname);
          	clearForm();
          }

          //删除:找到父元素,调用其removeChild("指定删除的元素")
          function removeRow(deptno){
          	var deptRow=document.getElementById("dept-"+deptno);
          	var dept=document.getElementById("dept-body");
          	dept.removeChild(deptRow);
          }

          function addRow(deptno,dname){
          	var trElt=document.createElement("tr");
          	trElt.setAttribute("id","dept-"+deptno);//设置tr的属性
          	var deptnoTd=document.createElement("td");
          	var dnameTd=document.createElement("td");
          	var delTd=document.createElement("td");
            
                 var delBtn=document.createElement("button");//创建button按钮
                 delBtn.appendChild(document.createTextNode("删除"));//追加文本数据
                 delBtn.addEventListener("click",function(){//添加事件
            	   removeRow(deptno);
                 },false);
            
                delTd.appendChild(delBtn);

          	deptnoTd.appendChild(document.createTextNode(deptno));
          	dnameTd.appendChild(document.createTextNode(dname));
          	trElt.appendChild(deptnoTd);
          	trElt.appendChild(dnameTd);
          	trElt.appendChild(delTd);
          	document.getElementById("dept-body").appendChild(trElt);
          }
    	</script>
    </head>

    <body>
        <div>
        	部门编号:<input type="text" name="deptno" id="deptno"/><br>
        	部门名称:<input type="text" name="dname" id="dname"/><br>
            <input type="button" value="增加" id="addBtn"/>
             <input type="button" value="清空" onclick="clearForm()"/>

        </div>

        <div>
    	<table border="1"  width="80%">
    		<thead >
    			<tr>
    			  <td>部门编号</td>
    			  <td>部门名称</td>
    			  <td>操作</td>
                 </tr>
    		</thead>
    		<tbody id="dept-body">
    			
    		</tbody>
    	</table>
    	</div>
    </body>
</html>

  

JavaScript操作DOM(动态表格处理)

原文:http://www.cnblogs.com/yuefeng123/p/7732619.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!