繁体   English   中英

动态插入 id 到表格元素中

[英]Dynamically insert id into table element

我正在从事我认为是一个简单的项目,但我正在努力解决这个问题。 我想知道是否有人可以查看我正在尝试做的事情,并就如何继续提供一些指导。

这里的概念相当简单......我想 - 根据“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();
      }
   }
}

当我运行上面的 js 代码时,在查看 Inspect Element Console 时没有错误,但是唯一的 id 永远不会插入到表元素中。

这应该通过 html 代码运行,识别每个表并动态应用(插入)一个唯一的 id 到每个表,但事实并非如此。

任何帮助是极大的赞赏。

这个 jQuery 选择器将查找所有具有 10 个或更多<tr>子项的表,并将 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();
     }
  );
});

这是一个 JSFiddle,基于您评论中的 on,它演示了它: https ://jsfiddle.net/5cgbdLzt/2/

在那个小提琴中,我添加了一个按钮来提醒您 ID,您可以在其中清楚地看到少于 10 行的表的 ID 的 ID 是undefined

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

暂无
暂无

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

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