【问题标题】:How dynamically change column title of dataTable jQuery plugin?如何动态更改 dataTable jQuery 插件的列标题?
【发布时间】:2015-06-09 12:56:33
【问题描述】:

我想更改由 jQuery Datatable 插件生成的数据表的列的标题

你知道我是否可以这样做:

 table = $('#example').DataTable({
        "data": source_dataTable,
        "columnDefs": defs,

    "dom": 't<"top"f>rt<"bottom"lpi><"clear">',
});
// WHAT I WANT TO DO:
    table.column(0).title.text("new title for the column 0")

?

它在第一行渲染一个 html:

 <table id="example" class="row-border hover dataTable no-footer" role="grid" aria-describedby="example_info" style="width: 1140px;">
   <thead>
       <tr role="row">
              <th class="sorting" tabindex="0" aria-controls="example" rowspan="1" colspan="1" aria-label="S&amp;#233;lectionn&amp;#233;: activer pour trier la colonne par ordre croissant" style="width: 94px;">Sélectionné</th>

               <th class="sorting" tabindex="0" aria-controls="example" rowspan="1" colspan="1" aria-label="Anglais : activer pour 

                  trier la colonne par ordre croissant" style="width: 

62px;">Anglais </th>

</tr>
</thead>
 </table>

...

在一个普通的表格中,下面的代码可以工作,但是对于由 jQuery 插件呈现的数据表,它不会:

$('#example tr:eq(0) th:eq(0)').text("Text update by code");

也许有 API 方法或其他 dom 方式?

【问题讨论】:

  • 示例应该是英文,而不是法文

标签: javascript jquery datatable datatables


【解决方案1】:

我找到了一个真正动态的解决方案

$(table.column(1).header()).text('My title');

【讨论】:

    【解决方案2】:

    使用下面的代码。检查DEMO

    如果第一个带有 td 的 tr

      $('table tr:eq(0) td:eq(0)').text("Text update by code");
    

    如果第一个 tr 和 th

      $('table tr:eq(0) th:eq(0)').text("Text update by code");
    

    当使用服务端进程或想要在数据表加载所有数据后执行一些操作时使用 Draw event

    Draw event - 在牌桌完成平局后触发

    例子

     $('#example').dataTable();
    
     $('#example').on( 'draw.dt', function () {
       console.log( 'Redraw occurred at: '+new Date().getTime() );
       $('#example tr:eq(0) th:eq(0)').text("Text update by code");
     } );
    

    使用回调。
    drawCallback 每次 DataTables 执行绘制时调用的函数。检查DEMO

       $('#example').dataTable( {
        "drawCallback": function( settings ) {
          $('#example tr:eq(0) th:eq(0)').text("Text update by code");
        }
      } );
    

    检查所有回调选项HERE

    【讨论】:

    • 谢谢,我确信它应该适用于经典表,但它不是用 jQuery 数据表生成的表
    • 它也适用于数据表。使用您用于数据表的表 id 添加代码 .. 你能告诉我你的代码吗?
    • 我编辑了这个问题,我试过 $('table#example tr:eq(0) th:eq(0)').text("Text update by code");但不起作用
    • 谢谢,是的,如果我直接编写呈现的 html,您的示例可以正常工作。但我不知道为什么,它不适用于 jQuery 数据表插件呈现的数据表(即使生成的 html 相同),也许它被插件阻止了,因为它是触发排序的地方,我不知道.感谢您的帮助。
    • 不,一旦数据表加载,您就可以编写此代码。有在数据表加载数据后调用的函数..我将使用数据表插件创建示例..明天
    【解决方案3】:

    可以这样:

    "columns": [{ sTitle: "Column1"},{ sTitle: "Column2"}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-13
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 2011-12-16
      • 1970-01-01
      相关资源
      最近更新 更多