描述:当用户点击添加数据的时候,表格的内容会自动添加,点击之前,只有表头吗,没有内容,内容是从服务器中取到的。所有jQuery版本是1.8.
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>动态创建表格</title>
<style>
table {
width: 500px;
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #c0c0c0;
}
th, td {
border: 1px solid #d0d0d0;
color: #404060;
padding: 10px;
}
th {
background-color: #09c;
font: bold 16px "微软雅黑";
color: #fff;
}
td {
font: 14px "微软雅黑";
}
tbody tr {
background-color: #f0f0f0;
}
tbody tr:hover {
cursor: pointer;
background-color: #fafafa;
}
</style>
<script src="jquery.min.js"></script>
<script>
$(function () {
//模拟从后台拿到的数据
var data = [{
name:"孙肖宁",
age:"20",
hobby:"编程"
},{
name:"小宁",
age:"22",
hobby:"读书"
}, {
name:"小宁博客",
age:"22",
hobby:"读书"
}];
$("#j_btnGetData").click(function () {
var ele = $("#j_tbData");
add(ele,data);
});
});
function add(ele,data) {
var arr = [];
for (var i = 0;i<data.length;i++){
arr.push("<tr><td>"+data[i].name+"</td><td>"+data[i].age+"</td><td>"+data[i].hobby+"</td></tr>");
}
var str = arr.toString();
ele.html(str);
}
</script>
</head>
<body>
<input type="button" value="获取数据" id="j_btnGetData"/>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>爱好</th>
</tr>
</thead>
<tbody id="j_tbData"></tbody>
</table>
</body>
</body>
</html>