想要 EasyUI 的表格功能,卻不想要它那套樣式。原本打算找現成外掛,翻了一輪沒找到合適的,索性自己寫——結果比想像中簡單。
public ActionResult GetDictTypes() {
var data = from a in dbo.DictTypes
select new DictTypeListViewModel {
ID = a.ID, Name = a.Name,
LastChangeUser = a.LastChangeUser,
LastChangeDate = a.LastChangeDate,
Remark = a.Remark
};
return Json(data.ToList());
}
<table class="table" id="DictTypeTable">
<thead>
<tr><th>ID</th><th>標題</th><th>簡介</th></tr>
</thead>
<tbody class="sel"></tbody>
</table>
這段要在 $(document).ready() 裡呼叫:
function ShowDictType() {
$('#DictTypeTable').children('tbody').empty();
$.ajax({
url: GetDictTypes_URL,
type: 'post',
dataType: 'json'
})
.done(function (data) {
var tbody = "";
$.each(data, function (index, el) {
var tr = "<tr>";
tr += "<td>" + el.ID + "</td>";
tr += "<td>" + el.Name + "</td>";
tr += "<td>" + el.Remark + "</td>";
tr += "</tr>";
tbody += tr;
});
$('#DictTypeTable').children('tbody').append(tbody);
BindDictTypeTableEvent(); // 資料回來後才綁事件
})
.fail(function () { alert("Err"); });
}
動態產生的 tr 不在頁面初始化時存在,所以事件一定要在資料插入之後才綁,這是最容易翻車的地方。
function BindDictTypeTableEvent() {
$('#DictTypeTable tbody.sel').children('tr').click(function (event) {
$(this).siblings('tr').removeClass('active'); // 清掉其他行的選中狀態
$(this).addClass('active'); // 標記目前行
var id = $(this).children('td:eq(0)').text(); // 取第一欄當主鍵
ShowDictData(id); // 後續動作,例如載入明細表
});
}
function GetTypeTableSelectId() {
return $('#DictTypeTable tbody.sel tr.active td:eq(0)').text();
}
整份實作只用了三個 API:$.ajax 抓資料、append 拼 DOM、addClass/removeClass 管選中態。樣式完全自己掌控,也不必背負整個框架的體積。