简体   繁体   English

使用 jQuery 和 dataTables 以编程方式创建表

[英]Programmatically create tables with jQuery and dataTables

I am using dataTables to render a table programmatically on a Django web app:我正在使用dataTables在 Django Web 应用程序上以编程方式呈现表:

jQuery jQuery

$(document).ready(function() {
    $("#dynamic0").html('<table cellpadding="0" cellspacing="0" border="0" class="display table table-striped table-bordered" id="peak_table_0"></table>');
    $('#peak_table_0').dataTable( {
        "aaData": {{ table_data|safe }},
        "aoColumns": {{ table_headings|safe }}
    });
});

HTML HTML

<div id="dynamic0"></div>

I am going to have many similar tables, where only the data will change, so I would like to automate the table creation.我将有许多类似的表,其中只有数据会发生变化,所以我想自动创建表。 I have tried to put the jQuery initializers in a loop, but in this case the tables don't render: jQuery我试图将 jQuery 初始值设定项放入循环中,但在这种情况下,表不会呈现: jQuery

$("div1").each(function(index) {
    var table_id = "peak_table_" + index
    $(this).html('<table cellpadding="0" cellspacing="0" border="0" class="display table table-striped table-bordered" id="'+table_id+'"></table>');

    $(table_id).dataTable( {
        "aaData": {{ table_data|safe }},
        "aoColumns": {{ table_headings|safe }}
    });
});

HTML HTML

<div1 id="dynamic0"></div1>
<div1 id="dynamic1"></div1>

I'm guessing the selectors are not identified properly.我猜选择器没有正确识别。 Any suggestions?有什么建议?

Change改变

div1

To

div

I have a hunch jQuery in the DOM chokes because it is not a valid HTML tag.我在 DOM chokes 中有一个预感 jQuery,因为它不是有效的 HTML 标记。

The following works.以下作品。 It was missing the '#' in table_id.它缺少 table_id 中的“#”。

$("div1").each(function(index){
      var table_id = "peak_table_"+index;
      $(this).html('<table cellpadding="0" cellspacing="0" border="0" class="display table table-striped table-bordered" id="'+table_id+'"></table>');
      $("#"+table_id).dataTable( {
          "aaData": {{ table_data|safe }},
          "aoColumns": {{ table_headings|safe }}
      });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM