Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:计算每个表的表行数,并向相应的元素返回一个值_Javascript_Html_Html Table - Fatal编程技术网

Javascript:计算每个表的表行数,并向相应的元素返回一个值

Javascript:计算每个表的表行数,并向相应的元素返回一个值,javascript,html,html-table,Javascript,Html,Html Table,我在一个网页上有三个表格。每个表都有一个嵌套在标记中的对应元素,我需要反映其各自表中的行数,减去首行和底行(-2)。当我使用单个表时,此代码工作正常: HTML表格片段: <table class="table" id="category"> <thead> <tr> <th><i class="fa fa-hashtag"></i> headache - <

我在一个网页上有三个表格。每个表都有一个嵌套在
标记中的对应元素,我需要反映其各自表中的行数,减去首行和底行(-2)。当我使用单个表时,此代码工作正常:

HTML表格片段:

<table class="table" id="category">
      <thead>
          <tr>
              <th><i class="fa fa-hashtag"></i> headache - <label class="label label-primary" id="tableBadge">0</span></th>
              <th><i class="fa fa-calendar"></i> Date Added</th>
              <th><i class="fa fa-cog"></i> Options</th>
          </tr>
      </thead>
      <tbody>
          <tr>
              <td>Test entry</td>
              <td>1/19/2016</td>
              <td>
              <a href="#" class="btn btn-success btn-xs"><i class="fa fa-pencil"></i></a>
              <a href="#" class="btn btn-primary btn-xs"><i class="fa fa-calendar"></i></a>
              <a href="#" class="btn btn-danger btn-xs"><i class="fa fa-trash"></i></a>
              </td>
          </tr>
          <tr>
              <td><a href="#" class="btn btn-default btn-xs"><i class="fa fa-plus"></i> add entry</a></td>
              </td>
          </tr>
      </tbody>
  </table>
然而,考虑到HTML的规则,ID对于元素来说是唯一的,我处于一个绑定中。使用
getElementsByClassName()
getElementsByTagName()
值返回0,告诉我它不工作。至少使用相同的语法

我在Google等网站上搜索了一个解决方案,但它们似乎是针对行的总量而定制的,而不是针对各自表的单个计数


任何帮助都将不胜感激。提前感谢。

尝试使用
查询选择器all
如下:

document.querySelectorAll('.table>thead>tr')


数组的长度可能是您要查找的答案

将id tableBadge更改为tableBadge_类别,类似于其他表格

“table_id”是table的id,您跨越的是tableBadge_table_id


getElementsByTagName和getElementsByClassNAme返回节点列表,您需要对它们进行迭代

window.addEventListener('load', function(e) {
    //This is a node list you must iterate
    var tables = document.getElementsByTagName('table');

    for (var i = 0; i < tables.length; i++) {
        //This loop will handle each tble selected
        var table = tables[i];
        var totalRows = table.rows.length;
        console.log(totalRows);
        //Add your code here
    }
}, false);
window.addEventListener('load',函数(e){
//这是一个必须迭代的节点列表
var tables=document.getElementsByTagName('table');
对于(变量i=0;i
虽然您已经接受了答案,但我建议下面的内容可能会稍微有用一点,而且对硬编码豁免的依赖性也会大大降低(因此对未来的维护噩梦也会减少)

也就是说,我的解决方案是将“页脚”放在
元素中,以便相关的
元素都包含在
元素中

我建议使用JavaScript函数:

// wrapping the function in an Immediately-Invoked Function Expression
// ("IIFE") in order that it runs immediately and does not require
// calling later:
(function() {

  // using 'let' (rather than var) to declare local variables, all
  // of which are available only within the block in which they're
  // declared; here we convert the NodeList returned by
  // document.querySelectorAll('span.label') into an Array, using
  // Array.from():
  let outputs = Array.from(document.querySelectorAll('span.label')),

  // declaring another variable for later use:
    tbodies;

  // iterating over each of the found 'span.label' elements
  // in the Array, using Array.prototype.forEach():
  outputs.forEach(function(span) {
    // the first argument (here 'span') is the current
    // array-element of the array over which we're iterating.

    // finding the closest ancestor <table> element from the
    // current span node, and then finding all the <tbody>
    // elements contained within that <table>, and converting
    // that NodeList to an Array, again using Array.from() to
    // do so:
    tbodies = Array.from(span.closest('table').querySelectorAll('tbody'));

    // updating the text-content of the span to:
    // the sum of the child <tr> elements found in each of
    // the <tbody> elements found within the <table>, using
    // Array.prototype.reduce() to reduce the Array to a single
    // (here numeric) value; here we use an Arrow Function
    // to add the number of children of the <tbody> element
    // to the initialValue of the reduce method (0, the
    // final argument following the comma):
    span.textContent = tbodies.reduce((initialValue, tbody) => a + tbody.children.length, 0);
  });

// here the function is invoked:
})();

头痛-
添加日期
选择权
测试条目
1/19/2016

能否显示您正在使用的完整的
?根据请求进行更新。计数是否动态变化,以及响应什么?还是在页面的整个“生命周期”内保持不变?其思想是,当创建新条目时,页面重新加载时计数将增加。我不太关心“实时更新”。在表中显示的“计数”(可能在元素
#tablebadge
中)应该是0,还是应该是1?实际上,我在问哪些行应该从计数中扣除,哪些应该被计数?你认为“标题”和“页脚”是哪一个?既然您使用的是
thead
tbody
,为什么不同时使用
tfoot
来清楚地包含您不想计数的行呢?这样做很好。非常感谢你!我建议稍作修改—不要获取table元素本身的
行.length
,而是获取tbody元素的
document.getElementById(table_id).tBodies[0].rows.length
,并放入“底层行”(这似乎有特殊含义,不能被视为正常的“条目”由于前面的行是)到
tfoot
元素中的,因此您不必减去“幻数”2,这意味着如果将另一个表行添加到thead中,您不必调整代码。这正是我所做的。非常感谢您的输入和Cuchu对我的帮助。行计数选项:var rowCount=$(“#myTable tr”).length;
window.addEventListener('load', function(e) {
    //This is a node list you must iterate
    var tables = document.getElementsByTagName('table');

    for (var i = 0; i < tables.length; i++) {
        //This loop will handle each tble selected
        var table = tables[i];
        var totalRows = table.rows.length;
        console.log(totalRows);
        //Add your code here
    }
}, false);
// wrapping the function in an Immediately-Invoked Function Expression
// ("IIFE") in order that it runs immediately and does not require
// calling later:
(function() {

  // using 'let' (rather than var) to declare local variables, all
  // of which are available only within the block in which they're
  // declared; here we convert the NodeList returned by
  // document.querySelectorAll('span.label') into an Array, using
  // Array.from():
  let outputs = Array.from(document.querySelectorAll('span.label')),

  // declaring another variable for later use:
    tbodies;

  // iterating over each of the found 'span.label' elements
  // in the Array, using Array.prototype.forEach():
  outputs.forEach(function(span) {
    // the first argument (here 'span') is the current
    // array-element of the array over which we're iterating.

    // finding the closest ancestor <table> element from the
    // current span node, and then finding all the <tbody>
    // elements contained within that <table>, and converting
    // that NodeList to an Array, again using Array.from() to
    // do so:
    tbodies = Array.from(span.closest('table').querySelectorAll('tbody'));

    // updating the text-content of the span to:
    // the sum of the child <tr> elements found in each of
    // the <tbody> elements found within the <table>, using
    // Array.prototype.reduce() to reduce the Array to a single
    // (here numeric) value; here we use an Arrow Function
    // to add the number of children of the <tbody> element
    // to the initialValue of the reduce method (0, the
    // final argument following the comma):
    span.textContent = tbodies.reduce((initialValue, tbody) => a + tbody.children.length, 0);
  });

// here the function is invoked:
})();