2013-06-12 21 views
1

考慮下面的代碼:數據表的jQuery供應動態數組的索引值

var aDataSet = [ 
    ['1', 'Trident','Internet Explorer 4.0','Win 95+','4','X'], 
    ['2', 'Fish','Internet Explorer 5.0','Win 95+','5','C'], 
    ['3', 'Pony','Internet Explorer 5.5','Win 95+','5.5','A'] 
]; 

$('#example').dataTable({ 
    "aaData": aDataSet, 
    "aoColumns": [ 
     { "sTitle": "Engine" }, 
     { "sTitle": "Browser" }, 
     { "sTitle": "Platform" }, 
     { "sTitle": "Version", "sClass": "customCSS-" +aDataSet['id']['Version'] }, 
     { "sTitle": "Grade", "sClass": "center" } 
    ] 
});  

我想是能夠查找當前正在處理aDataSet元素並獲取其Version信息反饋,這樣我可以在aoColumns樣式的上下文中進行字符串連接。以上不執行任何樣式。此修改:

{ "sTitle": "Version", "sClass": "customCSS-" +aDataSet[0]['Version'] } 

使一切匹配第零個索引(很明顯),但我希望我能以某種方式強制查找。任何見解都會被讚賞。

回答

3

嗯,我真的不認爲你擔心Version價值本身,因爲這只是數據表的標準虛擬數據,所以我冒昧地將它作爲css級聯的一部分使用名稱。 Version值包含點,並且這些會使css變得混亂。然後,考慮到這一點,並假設我明白你正在嘗試做的,這裏是去了解任務的一種方式,在jsbin如圖所示:

http://jsbin.com/onelev/2/edit

這裏的主要問題是使用fnRowCallback生成 表格單元格上的動態類名稱。

CSS的造型自定義單元格顏色

.customCSS-Trident, table.dataTable tr.even td.customCSS-Trident.sorting_1, table.dataTable tr.odd td.customCSS-Trident.sorting_1 { background-color: blue; color: #fff; } 
.customCSS-Fish, table.dataTable tr.even td.customCSS-Fish.sorting_1, table.dataTable tr.odd td.customCSS-Fish.sorting_1 { background-color: green; color: #fff; } 
.customCSS-Pony, table.dataTable tr.even td.customCSS-Pony.sorting_1, table.dataTable tr.odd td.customCSS-Pony.sorting_1 { background-color: brown; color: yellow; } 
.customCSS-Cabbage, table.dataTable tr.even td.customCSS-Cabbage.sorting_1, table.dataTable tr.odd td.customCSS-Cabbage.sorting_1 { background-color: pink; } 

的JavaScript

$(document).ready(function() { 
    var oTable = $('#example').dataTable({ 
     "aaData": aDataSet, 
     "aoColumnDefs": [ 
     { "aTargets": [ 0 ], 
      "sTitle": "#" 
     }, 
     { "aTargets": [ 1 ], 
      "sTitle": "Engine" 
     }, 
     { "aTargets": [ 2 ], 
      "sTitle": "Browser" 
     }, 
     { "aTargets": [ 3 ], 
     "sTitle": "Platform" 
     }, 
     { "aTargets": [ 4 ], 
      "sTitle": "Version" 
     },  
     { "aTargets": [ 5 ], 
      "sTitle": "Grade", 
      "sClass": "center" 
     } 
     ], 
     "fnRowCallback": function(nRow, aData, iDisplayIndex) { 
      $('td:eq(4)', nRow).addClass("customCSS-" + aData[1]);  
      return nRow; 
     }, 
    }); 
    }); 

HTML

 <table cellpadding="0" cellspacing="0" border="0" class="display" id="example"> 
     <thead> 
      <tr> 
      <th>#</th> 
      <th>Engine</th> 
      <th>Browser</th> 
      <th>Platform(s)</th> 
      <th>Engine version</th> 
      <th>CSS grade</th> 
      </tr> 
     </thead> 
     <tbody> 
     </tbody> 
    </table> 

附錄
當您對一個特定列進行排序時,DataTables會動態生成sorting_1類。如果您有複雜的用戶持有Shift鍵,然後單擊另一個列標題,則數據表生成另一個名爲sorting_2的類,依此類推。雖然用戶按多列進行排序的可能性很低,但可以通過爲這些額外情況添加額外的規則來處理這些情況。

+0

這是令人愉快的。我將把它整合到我的代碼中,如果成功將會接受你的答案。你有沒有考慮過這個例子給項目?因爲根據我見過的所有內容,我必須將這些內容嵌入到個人DIV中 – Woot4Moo