如何在jquery数据表中动态显示列标题

时间:2016-09-22 16:15:53

标签: jquery datatables

我有以下代码用于显示在数据表中具有属性和值的对象数组。但是这里的列标题是硬编码的,如下面的html代码所示。如何根据输入数据集使其动态化?

{{1}}

2 个答案:

答案 0 :(得分:10)

假设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/

玩得开心。

答案 1 :(得分:1)

这是从外部json提取它的答案

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="script.js"></script>
<div><table id="example"></div>

script.js

jQuery( document ).ready( function( $ ) {
        // Code using $ as usual goes here.

        $.ajax( {
            url: '1.json',
            dataType: "json",
            "success": function ( json ) {
              var tables = $("#example").DataTable({               
                dom : 'l<"#add">frtip',
                "language": {
    "paginate": {
      "previous": "<&nbsp;Previous",
      "next": "next&nbsp;>"
    }
  },
                "columnDefs": [ {
    "targets": 2,
    "createdCell": function (td, cellData, rowData, row, col) {
      if (( cellData > 3 ) && ( cellData < 30 )){
        $(td).css('color', 'green')
      }
      else
           if (( cellData > 31 ) && ( cellData < 50 )){
        $(td).css('color', 'orange')
      }
      else
           if (( cellData > 51 ) && ( cellData < 100 )){
        $(td).css('color', 'red')
      }
    }
  } ],
                "ajax": {
                    "url": "1.json",
                    "type": "POST",
                    "datatype": "json"
                },
                "columns": json.columns
            });
            $('<label/>').text('Search Column:').appendTo('#add')
$select = $('<select/>').appendTo('#add')
$('<option/>').val('0').text('Index').appendTo($select);
$('<option/>').val('1').text('Name').appendTo($select);
$('<option/>').val('2').text('Age').appendTo($select);
$('<option/>').val('2').text('Image').appendTo($select);
$('input[type="search"]').on( 'keyup change recheck', function () {
  var searchValue = $(this).val();
  var columnSearch = $select.val();

  $('#example').DataTable().columns().every(function() {
    //alert('hi');
        this.search('');
    }); 

  if(columnSearch == 'All'){
    tables.search(searchValue).draw();
  } else {
    tables.columns(columnSearch).search(searchValue).draw();
  }
 });
 $select.on('change', function() {
 $('#example').DataTable().search('').draw();
 $('input[type="search"]').trigger('recheck');
 });
            },

        } );
    });

1.json

{
   "data":[
      {
         "Index": 4,
         "Name": "Bob",
         "Age": 7,
         "Image": "None"
      },
      {
         "Index": 2,
         "Name": "Timmy",
         "Age": 4,
         "Image": "None"
      },
      {
         "Index": 3,
         "Name": "Heather",
         "Age": 55,
         "Image": "ddd"
      },
      {
         "Index": 5,
         "Name": "Sally",
         "Age": 22,
         "Image": "None"
      }
   ],
    "columns": [
        { "title": "Index", "data" : "Index" },
        { "title": "Name",  "data": "Name" },
        { "title": "Age", "data": "Age" },
        { "title": "Image", "data": "Image" }
    ]
}