2013-03-22 65 views
2

我們使用DataTables jQuery插件(http://www.datatables.net)創建可排序的表。該插件可以自動檢測每列中數據的數據類型。使用<th>屬性爲DataTable指定列數據類型

如果要指定自己列的數據類型,您添加「aoColumns」屬性,當你初始化數據表:

$('#accountTable').dataTable({ 
    "bPaginate": false, 
    "sScrollX": "100%", 
    "bScrollCollapse": true, 
    "aoColumns": [ 
     null, 
     null, 
     { "sType": "currency" }, 
     { "sType": "currency" } 
    ] 
}); 

注意,我下載了數據表的貨幣數據類型的插件。這很好。

但是,我擔心如果我們對錶列進行更改,我們會忘記回到JS中並更改數據表插件在該表上的初始化方式。

所以......這將是理想的,直接根據需要在表格指定的數據類型:

<table class="dataTables display"> 
    <thead> 
     <tr> 
     <th>Category</th> 
     <th>Product</th> 
     <th sType="currency">Cost</th> 
     <th sType="currency">Retail</th> 
     ... 

有沒有辦法做到這一點,無論是與數據表的默認功能(我可以」 t查找)或使用JS循環或其他東西來循環表中的標籤,並更新其中「sType」屬性存在的sType?

+0

使用HTML自定義數據屬性 - 只需在構建配置數據結構時選擇其內容。 – CBroe 2013-03-22 16:23:08

回答

1

感謝大家的幫助!我不得不做一些調整,以羅素Zahniser的評論它爲我工作:

  1. 改變$( '#accountTable>日')爲$( '#accountTable THEAD日')
  2. 更改aoColumns。 push(sType?sType:null)爲aoColumns.push(sType?{ 「S型」: 「貨幣」}:空)

最終結果:

var aoColumns = []; 

$('#accountTable thead th').each(function() { 
    var sType = $(this).getAttribute("data-sType"); 
    aoColumns.push(sType ? { "sType" : "currency" } : null); 
}); 

$('#accountTable').dataTable({ 
    ... 
    "aoColumns": aoColumns 
}); 
1

讓您的JS循環遍歷並檢查標頭上的屬性是否可行,但是您不能只發明sType屬性並將它顯示在DOM中。你必須破壞headers這樣的有效但未使用的屬性(這可能會給屏幕閱讀器帶來麻煩;可能會有更好的選擇)。

編輯:

OK,看了CBroe的評論,我想這可能give an element an arbitrary attribute.

所以,如果你想成爲HTML5兼容,你可以將該屬性命名爲data-sType,然後做這樣的事情:

var aoColumns = []; 

$('#accountTable > th').each(function() { 
    var sType = $(this).getAttribute("data-sType"); 
    aoColumns.push(sType ? sType : null); 
}); 

$('#accountTable').dataTable({ 
    ... 
    "aoColumns": aoColumns 
}); 
+0

太棒了!這幾乎是完美的。必須做一些小小的調整才能爲我工作。看到我的評論。 – 2013-03-22 21:05:07

1

接受CBroe的評論,這正是我所做的。只要確保您的自定義屬性的前綴爲data-,例如data-stype='currency'HTML specs

2

這裏絕對是一個辦法做到這一點:

頁眉HTML:

<table id="sorted-table"> 
    <thead> 
     <tr> 
      <th data-s-type="string">Number</th> 
      <th data-s-type="html">Complex Name</th> 
      <th>Price</th> 
      <th data-b-sortable="false">Action</th> 
     </tr> 
    </thead> 
... 

您的JS:

$('#sorted-table').dataTable({ 
    ... 
    "aoColumns": $('#sorted-table').find('thead tr th').map(function(){return $(this).data()}) 
}); 

注意:數據屬性中的破折號是必需的。他們通過jQuery將它轉換爲camelCase表格,這使得它與數據表API兼容。

+0

這是真的很棒的解決方案!好一個! – ppumkin 2016-02-17 11:31:45

相關問題