2016-04-12 68 views
2

是否可以將計算值綁定到數據表底層模型,以便.rows().data()包含以下代碼段中的列c將計算列值綁定到數據表數據模型

var data = [{ 
 
    a: 1, 
 
    b: 2 
 
}, { 
 
    a: 2, 
 
    b: 4 
 
}, { 
 
    a: 3, 
 
    b: 8 
 
}, { 
 
    a: 4, 
 
    b: 10 
 
}, ] 
 

 
var table = $('#dt').DataTable({ 
 
    data: data, 
 
    columns: [{ 
 
    title: "a", 
 
    data: "a" 
 
    }, { 
 
    title: "b", 
 
    data: "b" 
 
    }, { 
 
    title: "c", 
 
    data: null 
 
    }], 
 
    aoColumnDefs: [{ 
 
    aTargets: [2], 
 
    mRender: function(data, type, row) { 
 
     return row.a + row.b; 
 
    } 
 
    }] 
 

 
}); 
 

 
$('#log').click(function() { 
 
    var data = table.rows().data(); 
 
    // first row only 
 
    // logged -> {a: 1, b: 2} 
 
    // desired -> {a: 1, b: 2, c: 3} 
 
    console.log(data[0]); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<link href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css" rel="stylesheet" /> 
 
<script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script> 
 

 

 
<table id="dt"> 
 
    <thead> 
 
    <tr></tr> 
 
    </thead> 
 
</table> 
 

 
<button id="log">Log Data</button>

回答

2

您可以定義一個函數爲columns.data選項,並創造更多的數據屬性c

var table = $('#dt').DataTable({ 
    data: data, 
    columns: [{ 
    title: "a", 
    data: "a" 
    }, { 
    title: "b", 
    data: "b" 
    }, { 
    title: "c", 
    data: function(row, type, set, meta){    
     if(!row.hasOwnProperty('c')){ 
      row.c = row.a + row.b; 
     } 
     return row.c; 
    } 
    }] 
}); 

查看this jsFiddle的代碼和演示。