目标:
能够创建和添加节点
#题目描述:
用户在页面上点击按钮,可以把文本框中的数据在表格的新的一行中显示
具体表现如下图:
训练提示:
1.按钮注册单击事件
2.获取并判断文本框的内容
4.创建行并添加到tbody中
5.创建列,并设置内容
6.把列添加到行中
代码示例:
<style>
table {
width: 500px;
text-align: center;
}
td,
th {
border: 1px solid #333;
}
thead tr {
height: 40px;
background-color: pink;
}
</style>
<div id="dv">
姓名:
<input type="text" id="uname" placeholder="请输入姓名" />
<br /> 邮箱:
<input type="email" id="email" placeholder="请输入邮箱" />
</div>
<input type="button" value="添加" id="btn" />
<table border="1" cellpadding="0" cellspacing="0" id="tb">
<thead>
<tr>
<th>姓名</th>
<th>邮箱</th>
</tr>
</thead>
<tbody id="tbd">
<tr>
<td>小黑</td>
<td>xiaohei@126.com</td>
</tr>
</tbody>
</table>
<script>
// 1.获取对象
var userName = document.querySelector('#uname');
var userEmail = document.querySelector('#email');
var btn = document.querySelector('#btn');
//2. 查找添加标签位置
var tbody = document.getElementById('tbd');
btn.onclick = function() {
// 1.创建存储输入值的两个td,并通过innerHTML函数将输入数据回显
var newName = document.createElement('td');
newName.innerHTML = userName.value;
var newEmail = document.createElement('td');
newEmail.innerHTML = userEmail.value;
// 2.先在tbody内添加一个tr
var newTr = document.createElement('tr');
tbody.appendChild(newTr);
// 3.再通过新增的tr,将两个td添加到表格内
newTr.appendChild(newName);
newTr.appendChild(newEmail);
}
</script>