<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>简单留言本</title>
</head>
<body>
<label>请输入内容</label>
<input type="text" id="comment" autofocus="autofocus" onkeydown="addComment(this)"/>
<ul id="list">
</ul>
<script type="text/livescript">
function addComment(comment){
if(event.keyCode==13){
var item = document.createElement('li');
item.innerHTML=comment.value;
item.innerHTML += ' <button onclick="del(this)">删除</button>';
var list = document.getElementById('list');
if(list.childElementCount === 0){
list.appendChild(item);
}else{
var first = list.firstElementChild;
list.insertBefore(item,first);
}
comment.value='';
}
}
function del(ele){
return confirm("确定要删除吗?")?ele.parentElement.remove():false;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js操作表格的基本技巧</title>
<style>
table,th,td{
border: 1px solid #666;
}
table {
width: 500px;
text-align: center;
border-collapse: collapse;
}
table caption {
font-size: 1.2rem;
margin-bottom: 15px;
}
/* 这里必须在nth-of-type(1)前添加父元素,否则thead,tbody中的第一行都会生效 */
thead tr:nth-of-type(1) {
background-color: lightblue;
}
</style>
</head>
<body>
<table id="cart">
<caption>购物车</caption>
<thead>
<tr>
<th>编号</th>
<th>品名</th>
<th>数量</th>
<th>单价</th>
</tr>
</thead>
<tbody></tbody>
</table>
<hr>
<table id="cart2">
<caption>购物车2</caption>
<thead>
<tr>
<th>编号</th>
<th>品名</th>
<th>数量</th>
<th>单价</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
var data = [
{id: 1, name: '牛奶', count: 3, price: 50},
{id: 1, name: '苹果', count: 10, price: 80},
{id: 1, name: '衣服', count: 2, price: 600}
];
var cart = document.getElementById('cart');
var tbody = cart.children[2];
data.forEach(function (value){
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + value.id + '</td>';
tr.innerHTML += '<td>' + value.name + '</td>';
tr.innerHTML += '<td>' + value.count + '</td>';
tr.innerHTML += '<td>' + value.price + '</td>';
tbody.appendChild(tr);
});
var cart3 = document.getElementById('cart2');
var tbody = cart2.tBodies[0];
for (var i = 0; i < data.length; i++) {
var tr = document.createElement('tr');
Object.keys(data[i]).forEach(function(key){
tr.innerHTML += '<td>' + data[i][key] + '</td>';
});
tbody.appendChild(tr);
}
</script>
</body>
</html>