Javascript:计算每个表的表行数,并向相应的元素返回一个值
Javascript: Count number of table rows for each table and return a value to corresponding elements
我在网页上有三个表格。每个表都有一个嵌套在 <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
.
- Jquery在刷新时返回元素的旧值
- 什么'这是返回元素的好方法's路径
- Javascript函数无法返回元素
- getElementById 不返回元素
- JQuery .index() 不返回元素的正确索引
- Lodash Javascript 基于唯一属性值返回元素
- 为什么随机选择算法在 Array[low] 时返回元素(低 === 高)
- scrollTop() 返回元素下方的位置
- Jquery 返回元素的 .width() 取决于元素的找到方式
- D3 按类选择元素并返回元素 ID
- 移除.append()以向其返回元素'的原始状态
- 如何在Selenium Python execute_script中获取返回元素的值
- jQuery find-返回元素的顺序是什么
- 使用jQuery Mobile时未能返回元素的width()
- 数组的递归返回元素
- XML getElementsByTagName在Safari中不返回元素
- JavaScript shift()方法是否返回元素的引用或副本?
- 是否有官方的w3c声明指出用户代理实际上必须以大写形式返回元素的标记名称?
- jQuery在PC上返回元素ID,在Android上返回'undefined'为什么
- 在承诺后从jQuery插件返回元素