標籤:
模仿easyui的datagrid來做的,只做了個大概,後期慢慢最佳化和添加功能
css樣式
/* CSS Document */body { font: 14px/1.43 "Helvetica Neue", Tahoma, "Microsoft YaHei", Arial; color: #253443; margin: 0 auto; padding: 0 auto;}table { border-collapse: collapse; border-spacing: 0; background: #FFF; font-size: 12px; width: 100%; border: 1; width: 100%;}thead { display: table-header-group; vertical-align: middle; border-color: inherit;}tr { display: table-row; vertical-align: inherit; border-color: inherit;}table thead tr th { padding: 5px 8px; font-weight: normal; color: #999; border-bottom: 1px solid #B50802; vertical-align: bottom; line-height: 20px;}tbody { display: table-row-group; vertical-align: middle; border-color: inherit;}table tbody tr td { padding: 8px; border-top: 0px; border-bottom: 1px solid #DDD; vertical-align: middle; line-height: 20px; text-align: center;}.mouseover { background-color: #3A99AB; color: #FFF;}
自訂jquery
// JavaScript Document$(function () { var dataGrid = function (ele, opt) { this.defaults = { id: "", url: null, pageSize: 10, pageindex: 1 } this.settings = $.extend({}, this.defaults, opt); } dataGrid.prototype = { init: function () { this.create(); this.bindEvent(); }, create: function () { var json = this.getAjaxDate(this.settings.url, null); var id = this.settings.id; $("#" + id).append("<thead><tr></tr></thead><tbody></tbody>"); this.createTableHead(json.columns,id); this.createTableBody(json,id); }, //迴圈添加表頭 createTableHead: function (headcols,id) { for (var i = 0; i < headcols.length; i++) { $("#" + id).find("thead tr").append("<th>" + headcols[i].title + "</th>"); } },//迴圈添加行 createTableBody: function (json,id) {var rowsdata="";for(var rows=0;rows<json.data.length;rows++){rowsdata+="<tr>";for (var cols = 0; cols < json.columns.length;cols++) {rowsdata+=‘<td>‘ + json.data[rows][json.columns[cols].field] + ‘</td>‘;}rowsdata+="</tr>";}$("#" + id).find("tbody").append(rowsdata); }, bindEvent: function () { var id = this.settings.id; //添加滑鼠懸浮事件 $("#" + id).find("tbody tr").mouseover(function () { $(this).addClass("mouseover"); }).mouseleave(function () { $(this).removeClass("mouseover"); }); //添加隔行變色 //$("#" + id).find("tr:odd").css("background-color", "#A77C7B").css("color", "#fff"); }, getAjaxDate: function (url, parms) { //定義一個全域變數來接受$post的傳回值 var result; //用ajax的同步方式 $.ajax({ url: url, async: false, //改為同步方式 data: parms, success: function (data) { result = data; } }); return result; } } $.fn.grid = function (options) { var grid = new dataGrid(this, options); return this.each(function () { grid.init(); }); }})
html頁面調用
<!doctype html><html><head><meta charset="utf-8"><title>無標題文檔</title><script src="jquery-1.8.0.min.js"></script><link rel="stylesheet" type="text/css" href="style.css"><script src="pagetion.js"></script><script type="text/javascript">$(function(){ $("#dg").grid({ id:"dg", url:"data.json" }); });</script></head><body><form id="form1"><table id="dg"></table></form></body></html>
瀏覽器顯示
自訂jquery表格外掛程式