[英]JQuery loop through table get ID and change values in a specific column
我的页面有2-3个表格。 在这些表中,我想更改位于<thead>
中的特定列的文本以及每个<td>
行中的值,我想从每一行中获取id
。
从性能角度来看,最快的方法是什么?
表格布局:
<table class="ms-viewtable">
<thead id="xxx">
<tr class ="ms-viewheadertr">
<th>
<th>
<tbody>
<tr class="ms-itmHover..." id="2,1,0">
<td>
<td>
<tr class="ms-itmHover..." id="2,2,0">
<td>
<td>
</table>
我开始的脚本:
$('.ms-listviewtable').each(function () {
var table = $(this);
$table.find('tr > th').each(function () {
//Code here
});
$table.find('tr > td').each(function () {
//Code here
});
我如何获得ID? 这是做我想要的更好的方法吗?
您可以通过在"id"
上调用.attr
来获取元素的"id"
即$(this).attr("id");
。
在jquery中,获取任何元素的最佳方法是给它提供一个ID,然后对其进行引用。
我将以另一种方式构造它-为表元素提供有意义的ID,然后将我要检索的信息放入其类属性中。
<tr id="ms-itmHover..." class="2,2,0">
然后按如下方式检索它: $('#ms-itmHover...').attr('class');
您可以通过从表行“映射”到关联的ID来获得ID,因此:
var ids = $table.find('tbody > tr').map(function() {
return this.id;
}).get();
您可以使用表格行的.cells
属性访问单个单元格:
$table.each('tbody > tr', function() {
var cell = this.cells[i]; // where 'i' is desired column number
...
});
遍历所有表,收集所有行并根据您的需要找到它们的标识符:
$('table.ms-viewtable').each(function(){
$(this).find('tr').each(function(){
var cells = $(this).children(); //all cells (ths or tds)
if (this.parentNode.nodeName == 'THEAD') {
cells.eq(num).html('header row '+this.parentNode.id);
} else { // in "TBODY"
cells.eq(num).html('body row '+this.id);
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.