将id动态插入到表元素中



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

这里的概念相当简单。。。我认为-在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控制台时没有错误,但唯一的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,它证明了这一点:https://jsfiddle.net/5cgbdLzt/2/

在这个fiddle中,我添加了一个按钮,它将向您提醒ID,在那里您可以清楚地看到,少于10行的表的ID具有undefined的ID。

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

最新更新