jquery通過AJAX從后台獲取信息並顯示在表格上,並支持行選中


不想用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>

javascript代碼:(需要在 $(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");
     });
}

要在表格生成之后再綁定事件:

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);//操作代碼,這里是顯示另一個表格數據
    });
}

最后這里是獲取選中條目ID的代碼:

function GetTypeTableSelectId() {
    return $('#DictTypeTable tbody.sel tr.active td:eq(0)').text();
}

 


UPDATE in 2015-9-21

 新版:《jquery通過AJAX從后台獲取信息並顯示在表格上的類》,可以直接調用,不需要重新寫了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM