如何使用 Jquery / DataTables 根据单击的元素获取 table 的列名

how to get column name of a table based on clicked element using Jquery / DataTables

我有一个 Jquery DataTables and on footer I added a bootstrap-select 来过滤我的数据。

在下拉菜单 select 中,我添加了一个按钮“清除过滤器”,当有 is/are 个选项 select 时。

当我单击该按钮时,我需要获取 header 名称。

因此,在我的示例中,如果我单击“位置”列中的“清除过滤器”按钮,我应该提醒“位置'。 但它始终显示最后一列名称。

请给我任何建议我的代码中缺少什么?我添加了对我执行的步骤的详细说明。非常感谢。

$(document).ready(function() {

  var table = $('#example').DataTable({
    searching: false,
    info: false,
    paging: false,

    initComplete: function() {        
      this.api().columns().every(function() {
//add select to each column footer
        var column = this;
        var select = $('<select class="form-control show-tick" data-container="body" data-header="Select option(s)" data-actions-box="true" data-live-search="true" title="All" data-selected-text-format="count > 0" multiple></select>')
          .appendTo($(column.footer()).empty());
// populate the select options with unique values of current column          
        column.data().unique().sort().each(function(d, j) {
          select.append('<option value="' + d + '">' + d + '</option>');
        });

      });
//apply bootstrap selectpicker
      $("select").selectpicker();
//add 'clear filter' button below the search box in the dropdown select      
      var buttonPosition = $('.bs-searchbox');
         $('<div class="text-center"><button type="button" class="btn btn-sm btn-light clearButton">Clear filter</button></div>').appendTo(buttonPosition); 
//        
$(".clearButton").on("click", function(){
//check the closest <th> in the footer to the clicked button 
var tableFoot =$(this).closest('tfoot').find('th');
//console.log(tableFoot);
//we know the position of the button in which <th> on the footer and from it we will check the column name on header
alert('Column:'+$('table thead tr th').eq(tableFoot.index()).html().trim());
});
    }
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/css/bootstrap-select.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.17/js/bootstrap-select.min.js"></script>

<table id="example" class="table table-bordered table-hover nowrap" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Ashton Cox</td>
                <td>Junior Technical Author</td>
                <td>San Francisco</td>
            </tr>
            <tr>
                <td>Cedric Kelly</td>
                <td>Senior Javascript Developer</td>
                <td>Edinburgh</td>
            </tr>
            <tr>
                <td>Airi Satou</td>
                <td>Accountant</td>
                <td>Tokyo</td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
             </tr>
        </tfoot>
    </table>

问题是由于 Bootstrap select 不是显示的 table 的一部分,而是附加到 HTML 正文并且绝对位于 table 单元格上。

有一个配置选项 container: string | false 可用于 .selectpicker() 调用,因此您可以做的是在列上设置一个 ID 并设置要在此元素中呈现的选项。

    let cf = $(column.footer()).empty();
    var select = $('<select class="form-control show-tick" data-container="body" data-header="Select option(s)" data-actions-box="true" data-live-search="true" title="All" data-selected-text-format="count > 0" multiple></select>')
      .appendTo(cf).selectpicker({container: '#ci'+ci});
      cf.attr('id',  'ci' + ci).data('col', ci);

在你清晰的例程中:

  $(".clearButton").on("click", function() {
    var col = $(this).closest('th').data('col');
    alert('Column:' + $('table thead tr th').eq(col).html().trim());
  });

Fiddle 使用此解决方案。


另一种选择是在循环中创建一个引用当前列索引的对象,并显示 select 通过 show.bs.select 事件设置列索引:

    let obj= { ci: ci};
    var select = $('<select id="ci' + ci + '" class="form-control show-tick" data-container="body" data-header="Select option(s)" data-actions-box="true" data-live-search="true" title="All" data-selected-text-format="count > 0" multiple></select>')
      .appendTo($(column.footer()).empty()).selectpicker().on('show.bs.select',  function() {
        window.currentSelect = obj.ci;
      });

并且在清晰的例程中:

  $(".clearButton").on("click", function() {
    alert('Column:' + $('table thead tr th').eq(window.currentSelect).html().trim());
  });

Fiddle 使用替代解决方案。