DOM练习

对表格进行添加一行、删除、变色操作:

 1 <button id="add">添加一行</button>
 2 <table id="tab" border="1" width="100%" height="50px" cellspadding="0" cellspacing="1">
 3     <tr>
 4         <td>编号</td>
 5         <td>姓名</td>
 6         <td>性别</td>
 7         <td>年龄</td>
 8         <td>住址</td>
 9         <td>操作</td>
10     </tr>
11     <tr id="bs">
12         <td>007</td>
13         <td>薛之谦</td>
14         <td></td>
15         <td>33</td>
16         <td>火星</td>
17         <td>
18         <button id="btr">删除</button>
19         <button onClick="bianse(this)">变色</button>
20         </td>
21     </tr>
22     <tr id="hf">
23         <td>008</td>
24         <td>大黄蜂</td>
25         <td></td>
26         <td>未知</td>
27         <td>未知</td>
28         <td>
29             <button id="shc" onClick="shanchu(this)">删除</button>
30         </td>
31     </tr>
32 </table>

JS代码:

 1 window.onload = function(){
 2     var addbtn=document.getElementById("add");
 3     var tab=document.getElementById("tab");
 4     addbtn.onclick=function(){
 5         var tr=document.createElement('tr');
 6         tab.appendChild(tr);
 7         for (var i = 0; i <=5; i++){
 8             var td=document.createElement('td');
 9             tr.appendChild(td);
10             if(i<=4){
11                  td.innerHTML="薛之谦";
12             }else{
13                 var button=document.createElement("button");
14                 button.innerHTML="删除";
15                 td.appendChild(button);
16                 button.onclick=function(){
17                         button.parentNode.parentNode.remove();
18                     
19                 }
20             }
21         }
22     }
23      var shbtn=document.getElementById("shc");
24      var tr=document.getElementById("hf");
25     var tr=document.getElementById("bs");
26 }
27 function shanchu(obj){
28     obj.parentNode.parentNode.remove();
29     
30 }
31 function bianse(obj){
32    obj.parentNode.parentNode.style.background="red";    
33 }

简易计算器:

 1 <input type="text" id="shu">
 2 <select name="#" id="post">
 3        <option>+</option>
 4     <option>-</option>
 5     <option>*</option>
 6     <option>/</option>
 7 </select>
 8     <input type="text" id="shu1">
 9     <input id="jg" type="button" value="=" onClick="dj()">
10     <input id="sum" type="text">

JS实现代码:

 1 var zhi="";
 2 function dj(){
 3     var a=document.getElementById("shu");
 4     var x=a.value;
 5     var b=document.getElementById("shu1");
 6     var y=b.value;
 7     var c=document.getElementById("post");
 8     var z=c.value;
 9     var d=document.getElementById("sum");
10     
11     if(z==="+"){
12        var zhi=x+y;
13        }else if(z==="-"){
14         var zhi=x-y;
15     }else if(z==="*"){
16              var zhi=x*y;
17              }else if(z==="/"){
18                     var zhi=x/y;
19              }
20     d.value=zhi;
21 }  

 

posted @ 2018-06-24 12:58  文昭  阅读(162)  评论(0编辑  收藏  举报