运行截图
HTML 结构
<body>
<table>
<thead>
<tr>
<th>歌名</th>
<th>歌手</th>
<th>专辑</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
CSS 样式
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
a {
text-decoration: none;
}
table {
width: 800px;
margin: 100px auto;
text-align: center;
border-collapse: collapse;
font-size: 14px;
}
thead tr {
height: 30px;
color: #fff;
background-color: skyblue;
}
thead tr th {
border: 1px solid #00a1d6;
}
tbody tr {
height: 30px;
}
tbody td {
border: 1px solid #00a1d6;
font-size: 12px;
color: #555;
margin-right: -1px;
}
</style>
JavaScript 代码
<script>
//歌曲的构造函数
function Song(songname, singer, album) {
this.songname = songname;
this.singer = singer;
this.album = album;
}
var num = parseInt(prompt('请输入要录入的歌曲数量'));
var tbody = document.querySelector('tbody');
for (var i = 1; i <= num; i++) {
//创建 tr行
var tr = document.createElement('tr');
tbody.appendChild(tr);
// 从键盘读取歌曲信息
var songname = prompt('请输入第' + i + '首歌的歌名');
var singer = prompt('请输入第' + i + '首歌的歌手');
var album = prompt('请输入第' + i + '首歌的专辑名');
//利用构造函数 生成song对象
var song = new Song(songname, singer, album);
//行里面创建单元格
for (var k in song) {
var td = document.createElement('td');
td.innerHTML = song[k];
tr.appendChild(td);
}
//增加删除表格
var td = document.createElement('td');
td.innerHTML = "<a href = 'javascipt:;'>删除</a>";
tr.appendChild(td);
//删除操作
td.onclick = function () {
tbody.removeChild(this.parentElement);
}
}
</script>
删除操作的另一种做法(事件委托)
tr.addEventListener('click', function (e) {
tbody.removeChild(e.target.parentNode.parentNode);
})
版权声明:本文为m0_50789696原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。