在網頁中動態地給表格添加一行內容--HTML+CSS+JavaScript


需求描述:

用戶在頁面上點擊按鈕,可以把文本框中的數據在表格的新的一行中顯示,具體表現如下圖:

如果如果輸入框內容有一項為空,彈出對話框‘請將數據填入完全

              

步驟:

1.按鈕注冊單擊事件

2.獲取並判斷文本框的內容

4.創建行並添加到tbody中

5.創建列,並設置內容

6.把列添加到行中

代碼:
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>在網頁中添加表格</title>
 6     <style>
 7         * {
 8             margin: 0;
 9             padding: 0;
10         }
11 
12          div {
13              width: 400px;
14              margin: 100px auto;
15          }
16         table {
17             margin-top: 10px;
18             width: 400px;
19             border: 2px solid #000;
20             border-collapse: collapse;
21         }
22         table thead tr {
23             background-color: purple;
24             color: #e0e0e0;
25         }
26 
27         table tr {
28             background-color: pink;
29         }
30 
31         table td {
32             text-align: center;
33             border:1px solid #000 ;
34         }
35 
36         table td:nth-child(1){
37             width: 100px;
38         }
39 
40         table td:nth-child(2){
41             width: 300px;
42         }
43     </style>
44 </head>
45 <body>
46 <div>
47     <label for="">請輸入姓名:</label>
48     <input type="text" class="uname"><br />
49     <label for="">請輸入郵箱:</label>
50     <input type="email" class="email"><br />
51     <button>添加</button><br />
52     <table>
53         <thead>
54         <tr>
55             <td>姓名</td>
56             <td>郵箱</td>
57         </tr>
58         </thead>
59         <tbody>
60             <!--    動態添加內容  -->
61         </tbody>
62     </table>
63 </div>
64 
65 <script>
66     // 獲取元素
67     var uname = document.querySelector('.uname');
68     var email = document.querySelector('.email');
69     var btn = document.querySelector('button');
70     var tbody = document.querySelector('tbody');
71 
72     btn.onclick =function () {
73         //檢測輸入的內容不為空
74         if(uname.value === '' || email.value === '')
75             alert('請輸入內容');
76         else {
77             //創建節點
78             var tr = document.createElement('tr');
79             var td1 = document.createElement('td');
80             var td2 = document.createElement('td');
81             //獲取元素內容
82             td1.innerHTML = uname.value;
83             td2.innerHTML = email.value;
84             //添加內容到表格中
85             tr.append(td1);
86             tr.append(td2);
87             tbody.append(tr);
88         }
89     }
90 </script>
91 
92 </body>
93 </html>

效果:

現在輸入:name: 小明   --> 點擊添加按鈕添加


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM