Home >Web Front-end >JS Tutorial >JQuery obtains information from the background through AJAX and displays it on the table and supports row selection_jquery
I didn’t want to use Easyui’s style, but I wanted its table function. I originally wanted to look for related plug-ins online, but when I couldn’t find them, I started writing it myself. I didn’t expect it to be so easy.
Backend code: (This is not important)
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()); }
Page code:
<table class="table" id="DictTypeTable"> <thead> <tr> <th>ID</th> <th>标题</th> <th>简介</th> </tr> </thead> <tbody class="sel"></tbody> </table>
javascript code: (needs to be called in $(document).ready(function ($){ })
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"); }); }
To bind the event after the form is generated:
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();//获取ID ShowDictData(id);//操作代码,这里是显示另一个表格数据 }); }
Finally here is the code to get the ID of the selected item:
function GetTypeTableSelectId() { return $('#DictTypeTable tbody.sel tr.active td:eq(0)').text(); }