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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39644079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:13:43  来源:igfitidea点击:

How to display the column headers dynamically in jquery data table

jquerydatatables

提问by Bruce

I have the below code for displaying array of objects having property and a value in a data table. But here the column headers are hardcoded as seen in my below html code. How can I make it dynamic based on the input dataset?

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

 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>

回答by nanytech

Assuming the structure of the objects in the dataSet does not change, you could use the first object to build the json object external to the DataTable declaration. If the objects are not of a consistent structure, then you can tweak the logic inside the $.each structure to handle that.

假设 dataSet 中对象的结构没有改变,您可以使用第一个对象来构建 DataTable 声明外部的 json 对象。如果对象的结构不一致,那么您可以调整 $.each 结构中的逻辑来处理它。

Here's a quick hack:

这是一个快速的黑客:

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
  });
});

You should also consider removing all the static table content in your HTML like this

您还应该考虑像这样删除 HTML 中的所有静态表格内容

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

Here's the jsFiddle https://jsfiddle.net/z4t1po8o/18/

这是 jsFiddle https://jsfiddle.net/z4t1po8o/18/

Have fun.

玩得开心。

回答by ankush

Here is the answer to fetch it from external json

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

HTML

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

脚本.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

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" }
    ]
}