简体   繁体   English

将javascript变量附加到HTML属性

[英]Appending a javascript variable to an HTML property

I have multiple tables which are output via a php function. 我有多个通过php函数输出的表。 The tables are then to be formatted with the DataTables plugin, which requires me to reference the table ID's after the document is ready: 然后使用DataTables插件对表进行格式化,这需要我在准备好文档后引用表ID:

$(document).ready( function () {
   for (i = 0; i < ntables; i++) { 
       $('#Main_Data_Table'+i).DataTable();
   }
} );

So when I'm creating the tables I simply want to append the table number (ntables) to the id kind of like the following: 因此,当我创建表时,我只想将表号(ntables)附加到id上,如下所示:

<script>ntables++;</script>
<table id="Main_Data_Table<script>echo ntables</script>" class="display">

I'm used to using PHP, hence the echo which of course doesn't work. 我习惯使用PHP,因此回声当然是行不通的。 How do I simply append the ntables variable to the ID when I'm creating the tables? 创建表时,如何简单地将ntables变量附加到ID?

If you want to create HTML elements with dynamic IDs, you need to do use a loop in a programming language. 如果要创建带有动态ID的HTML元素,则需要使用一种编程语言进行循环。 You can use a server-side script to create the HTML, or build all the tables in Javascript: 您可以使用服务器端脚本来创建HTML,或使用Javascript构建所有表:

for (var i = 0; i < ntables; i++) {
    $("#container").append($("<table>", { 
        id: "Main_Data_Table_" + i,
        "class": "display"
    }).DataTable());
}

JS way JS方式

$(document).ready( function () {

    var tables = $("table.display");

    for(i = 1; i <= tables.length; i++){
      $(tables[i]).attr("id", "Main_Data_Table"+i);
    }    

} );

So in your php code you would just need to generate a bunch of tables with class="display" 因此,在您的php代码中,您只需要生成一堆带有class="display"的表

The best way is to add id directly from PHP when you are printing tables. 最好的方法是在打印表时直接从PHP添加ID。 If, for some reason, this is not possible, then you could try .getElementsByClassName("some class") then change each element id. 如果由于某种原因无法执行此操作,则可以尝试.getElementsByClassName(“ some class”)然后更改每个元素ID。

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

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