简体   繁体   English

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

[英]Javascript: Count number of table rows for each table and return a value to corresponding elements

I have three tables on a web page. 我的网页上有三个表格。 Each table has a corresponding element nested in <thead> tags that I need to reflect the number of rows in its respective table, minus the head row and bottom row (-2). 每个表都有一个嵌套在<thead>标记中的对应元素,我需要反映出各自表中的行数,减去头行和底行(-2)。 When I'm working with a single table, this code works just fine: 当我使用单个表时,此代码可以正常工作:

HTML Table Snippet: 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>

Javascript: 使用Javascript:

function catCount() {
    var rows = document.getElementById("category").rows.length;
    document.getElementById("tableBadge").innerHTML = rows - 2 + " entries";
}

However, respecting the laws of HTML in that ID's are unique to an element, I'm left in a bind. 但是,由于ID是元素唯一的,因此要尊重HTML的规律,因此我处于束缚之中。 Using getElementsByClassName() or getElementsByTagName() the values return 0, telling me it's not working. 使用getElementsByClassName()getElementsByTagName()值返回0,告诉我它不起作用。 At least using identical syntax. 至少使用相同的语法。

I've searched Google et al. 我已经搜索过Google等。 for a solution, but they seem to be tailored towards the total amount of rows, rather individual counts respective of their tables. 一个解决方案,但它们似乎是针对行的总数而设计的,而不是针对各自表的单独计数。

Any help would be appreciated. 任何帮助,将不胜感激。 Thank you in advance. 先感谢您。

change id tableBadge to tableBadge_category and similar to othter tables. 将id tableBadge更改为tableBadge_category,类似于其他表。

' table_id ' is a id of table and you span is tableBadge_ table_id ' table_id '是表的ID,跨度是tableBadge_ table_id

function catCount(table_id) {
    var rows = document.getElementById(table_id).rows.length;
    document.getElementById("tableBadge_"+table_id).innerHTML = rows - 2 + " entries";
}


catCount('category');
catCount('other_table');

Try instead using the querySelectorAll like: 尝试改用querySelectorAll类的方法:

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

The length of the array may be the answer you are looking for 数组的长度可能是您要寻找的答案

getElementsByTagName and getElementsByClassNAme return node list, you need to iterate over them. 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);

While you've already accepted an answer, I'd suggest that the following might be slightly more useful, and far less-reliant on hard-coding exemptions (and therefore less of a maintenance nightmare for the future). 尽管您已经接受了答案,但我建议以下内容可能会更有用,并且对硬编码豁免的依赖程度会大大降低(因此,将来对维护的噩梦会更少)。

That said, my solution involves placing the 'footer' inside of a <tfoot> element, in order that the relevant <tr> elements are all contained within the <tbody> element(s) of the <table> . 就是说,我的解决方案涉及将'footer'放置在<tfoot>元素内,以使相关的<tr>元素全部包含在<table><tbody>元素内。

The JavaScript function I'd recommend: 我建议使用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:
})();

 (function() { let outputs = Array.from(document.querySelectorAll('span.label')), tbodies; outputs.forEach(function(span) { tbodies = Array.from(span.closest('table').querySelectorAll('tbody')); span.textContent = tbodies.reduce((initialValue, tbody) => initialValue + tbody.children.length, 0); }); })(); 
 <table class="table category"> <thead> <tr> <th><i class="fa fa-hashtag"></i> headache - <span class="label label-primary"></span> </th> <th><i class="fa fa-calendar"></i> Date Added</th> <th><i class="fa fa-cog"></i> Options</th> </tr> </thead> <tfoot> <tr> <td colspan="2"><a href="#" class="btn btn-default btn-xs"><i class="fa fa-plus"></i> add entry</a> </td> </tr> </tfoot> <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> </tbody> </table> 

JS Fiddle demo . JS小提琴演示

It's worth noting that the above approach will handle multiple <table> elements each with, potentially, multiple <tbody> elements; 值得注意的是,上述方法将处理多个<table>元素,每个元素可能包含多个<tbody>元素; and requires no hard-coding of values to discount from the final count, since it selects only those elements that should be counted. 并不需要对值进行硬编码以从最终计数中扣除,因为它仅选择那些计数的元素。

References: 参考文献:

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

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