<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { margin: 0; padding: 0; } table { width: 500px; margin: 20px auto; border: 1px solid #333; border-collapse: collapse; } table td, table th { border: 1px solid #222; padding: 20px; text-align: center; } </style> </head> <body> <form action="" onsubmit="return false"> <label for="">id</label> <input type="text" id="id" class="input"> <label for="">姓名</label> <input type="text" id="username" class="input"> <label for="">年龄</label> <input type="text" id="age" class="input"> <button id="button">添加</button> </form> <table> <thead> <tr> <th>id</th> <th>姓名</th> <th>年龄</th> </tr> </thead> <tbody> </tbody> </table> <script> var ins = document.querySelectorAll('.input'); var btn = document.querySelector('#button'); console.log(ins, btn); btn.onclick = function () { var tbody = document.querySelector('table tbody'); // 查到tbody var b_tr = document.createElement('tr'); // 添加tr tbody.appendChild(b_tr); // 在tbody里面追加tr for (var k = 0; k < ins.length; k++) { var pd = ins[k].value; console.log(pd); if (pd.trim().length == 0) { alert('请完善表单信息'); return; } } for (var i = 0; i < 3; i++) { var td = document.createElement('td'); b_tr.appendChild(td); // 在tr里面追加td td.innerHTML = ins[i].value; // 清空数据 ins[i].value = ''; } // tbody.appendChild(b_tr); // 在tbody里面追加tr } </script> </body> </html>