2016-09-22 56 views
0

我有下面的代碼來顯示在數據表中具有屬性和值的對象數組。但是這裏的列標題是硬編碼的,如我在下面的html代碼中所見。我如何根據輸入數據集使其動態化?如何在jQuery數據表中動態顯示列標題

var dataSet = [{ 
    "Latitude": 18.00, 
    "Longitude": 23.00, 
    "Name": "Pune" 
}, { 
    "Latitude": 14.00, 
    "Longitude": 24.00, 
    "Name": "Mumbai" 
}, { 
    "Latitude": 34.004654, 
    "Longitude": -4.005465, 
    "Name": "Delhi" 
},{ 
    "Latitude": 23.004564, 
    "Longitude": 23.007897, 
    "Name": "Jaipur" 
}]; 
$(document).ready(function() { 
    $('#example').DataTable({ 
     data: dataSet, 
     "columns": [ 
      { "data": "Name" ,"title":"Custom Name"}, 
      { "data": "Latitude" }, 
      { "data": "Longitude" }, 

     ] 
    }); 
}); 




<table id="example" class="display" cellspacing="0" width="100%"> 
     <thead> 
      <tr> 
       <th>Name</th> 
       <th>Latitude</th> 
       <th>Longitude</th> 

      </tr> 
     </thead> 

    </table> 

回答

4

假設dataSet中對象的結構沒有改變,您可以使用第一個對象來構建DataTable聲明外部的json對象。如果對象的結構不一致,那麼可以調整$ .each結構中的邏輯來處理該對象。

這裏有一個快速的黑客:

var dataSet = [{ 
    "Latitude": 18.00, 
    "Longitude": 23.00, 
    "Name": "Pune" 
}, { 
    "Latitude": 14.00, 
    "Longitude": 24.00, 
    "Name": "Mumbai" 
}, { 
    "Latitude": 34.004654, 
    "Longitude": -4.005465, 
    "Name": "Delhi" 
}, { 
    "Latitude": 23.004564, 
    "Longitude": 23.007897, 
    "Name": "Jaipur" 
}]; 

var my_columns = []; 

$.each(dataSet[0], function(key, value) { 
     var my_item = {}; 
     my_item.data = key; 
     my_item.title = key; 
     my_columns.push(my_item); 
}); 

$(document).ready(function() { 
    $('#example').DataTable({ 
    data: dataSet, 
    "columns": my_columns 
    }); 
}); 

你也應該考慮在你的HTML刪除所有靜態表的內容是這樣

<table id="example" class="display" cellspacing="0" width="100%"></table> 

這裏的的jsfiddle https://jsfiddle.net/z4t1po8o/18/

有樂趣。

相關問題