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

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

本文关键字:返回 元素 一个 计算 Javascript      更新时间:2023-09-26

我在网页上有三个表格。每个表都有一个嵌套在 <thead> 标签中的相应元素,我需要反映其各自表中的行数,减去头行和底行 (-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>

Javascript:

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

但是,尊重HTML的定律,因为ID对于元素是唯一的,我陷入了困境。使用 getElementsByClassName()getElementsByTagName() 值返回 0,告诉我它不起作用。至少使用相同的语法。

我已经在Google等人那里搜索了解决方案,但是它们似乎是针对行总数量身定制的,而不是针对其表格中的单个计数。

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

将id tableBadge更改为tableBadge_category,类似于其他表。

">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');

尝试使用如下querySelectorAll

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

数组的长度可能是您正在寻找的答案

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);

虽然你已经接受了答案,但我建议以下内容可能更有用,并且对硬编码豁免的依赖程度要低得多(因此对未来的维护噩梦更少(。

也就是说,我的解决方案涉及将"页脚"放置在<tfoot>元素内,以便相关的<tr>元素都包含在<table><tbody>元素中。

我推荐的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小提琴演示。

值得注意的是,上述方法将处理多个<table>元素,每个元素可能具有多个<tbody>元素;并且不需要硬编码值以从最终计数中打折,因为它只选择那些应该计数的元素。

引用:

  • Array.from() .
  • Array.prototype.forEach() .
  • Array.prototype.reduce() .
  • 箭头函数。
  • document.querySelectorAll() .
  • Element.closest() .
  • let .