Javascript 在表元素中动态插入id

Javascript 在表元素中动态插入id,javascript,dynamic,html-table,Javascript,Dynamic,Html Table,我正在做一个我认为很简单的项目,但这是我正在努力解决的问题。我想知道是否有人能回顾一下我正在尝试做的事情,并给我一些关于如何继续的建议 这里的概念相当简单…我想-根据“table”元素识别html文件中的每个表,计算每个表中的行数,如果表中有10行以上,则动态创建表的唯一id 我知道如何做这一切(大部分),但它没有回应我的预期 下面是我最初尝试动态创建和插入唯一表id的javascript代码: /* This function dynamically sets a unique id to e

我正在做一个我认为很简单的项目,但这是我正在努力解决的问题。我想知道是否有人能回顾一下我正在尝试做的事情,并给我一些关于如何继续的建议

这里的概念相当简单…我想-根据“table”元素识别html文件中的每个表,计算每个表中的行数,如果表中有10行以上,则动态创建表的唯一id

我知道如何做这一切(大部分),但它没有回应我的预期

下面是我最初尝试动态创建和插入唯一表id的javascript代码:

/* This function dynamically sets a unique id to each table found in the html page: */
function set_table_id(){
   var num_tables = document.getElementsByTagName("table"); //determine the number of “table” nodes in the html
   //alert("set_table_id function: The total number of table elements are: " + num_tables.length);

   if (num_tables) { //if one or more table nodes are found…
      var id_name = "dataTbl_"; // create the prepend string for table id value
      var n = 1;
      var i;
      
      //for each table node found…
      for (i=0; i < num_tables.length; i++) {
         var id_name_new = id_name + n; //create the next unique table id from the prepend string
         n++;

         num_tables[i].id = id_name_new; //apply the latest table id to the current table

         //this will be the call to the function to apply the datatables javascript to each table that has more than 10 rows:
         //num_tables[i].dataTable();
      }
   }
}
/*此函数为html页面中找到的每个表动态设置唯一id:*/
函数集\表\ id(){
var num_tables=document.getElementsByTagName(“table”);//确定html中“table”节点的数量
//警报(“set_table_id函数:表元素总数为:“+num_tables.length”);
如果(num_tables){//如果找到一个或多个表节点…
var id_name=“dataTbl”;//为表id值创建前置字符串
var n=1;
var i;
//对于找到的每个表节点…
对于(i=0;i
当我运行上面的js代码时,当我查看Inspect元素控制台时没有错误,但是惟一id从未插入到表元素中

这应该贯穿html代码,识别每个表,并动态地为每个表应用(插入)一个唯一的id,但事实并非如此


非常感谢您的帮助。

此jQuery选择器将查找包含10个或更多子级的所有表,并将ID和DataTables应用于每个表

$(document).ready(function() {
  $("table > tbody > tr:nth-child(10)").closest("table").each(function(index) {
        var tableId = "dataTbl_" + (index + 1); //index is zero-based, so add 1
        $(this).attr("id", tableId); //set the ID attribute
        $(this).dataTable();
     }
  );
});
下面是一个JSFIDLE,基于您评论中的on,它演示了:

在这个提琴中,我添加了一个按钮,可以向您提示ID,您可以清楚地看到,少于10行的表的ID有一个未定义的ID


注意:DataTables使用jQuery作为依赖项,因此假设您可以使用jQuery选择器,而不是严格意义上的普通JS。

您是否意识到不需要单独初始化每个DataTable?您只需执行
$(“table”).dataTable()。嘿,马克-谢谢你的回复。尽管实现代码不会产生任何错误,但它不会在table元素中创建id。我在htm中定义了两个表-一个有54行,第二个有9行。我已经在htm内部和外部的函数中运行了脚本。我定义了一个警报,以确保tableId字符串是按原样创建的——它只是没有作为table元素的属性插入正在应用于htm中的两个表,而它只应应用于超过10行的表。我认为您需要在类似JSFIDLE的东西中创建一个示例,以便我们可以确切地看到您正在使用的内容。我在JSFIDLE上创建了一个帐户,下面是指向该项目的链接: