index部分代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
tr,
th,
td {
border: 1px solid blue;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="jQuery-bgc.js"></script>
<script>
$(function() {
$('div').table(['序号', '姓名', '年龄', '工资'], [{
n: 'xy',
age: 20,
s: 10
}, {
n: 'wy',
age: 20,
s: 8
}, {
n: 'pp',
age: 21,
s: 12
}]);
});
</script>
jQuery-bgc.js部分代码:
(function($) {
$.fn.table = function(tableh, tableb) {
var list = [];
list.push('<table>');
//头部
list.push('<thead>');
for (var i = 0; i < tableh.length; i++) {
list.push('<td>');
list.push(tableh[i]);
list.push('</td>');
}
list.push('</thead>');
//body
for (var i = 0; i < tableb.length; i++) {
list.push('<tr>');
list.push('<td>' + (i + 1) + '</td>');
for (const key in tableb[i]) {
list.push('<td>');
list.push(tableb[i][key]);
list.push('</td>');
}
list.push('</tr>');
}
list.push('</table>');
this.html(list.join(''));
};
}(jQuery));
生成表格如图: