我在下面定义了一个表元素,$table
.我正在尝试在每个单元格上运行一个函数,该单元格由特定表标题定义 - qc_statusTh
.我找到了该表标题(qc_statusColumnIndex
(的索引,并且能够抓取该列中的下一个表格单元格 - qc_statusCell
.
但是,我无法遍历表格单元格并在该列中的每个表格单元格上运行函数。
这是我到目前为止的JavaScript代码:
$(document).ready(function() {
var $table = $("table.tables.list");
if ($table.length > 0) {
var qc_statusTh = $("th.headersub:contains('qc_status')");
var qc_statusColumnIndex = $(qc_statusTh).index();
var qc_statusCell = $($table).find("td").eq(qc_statusColumnIndex);
// this does not work. this only replaces the first cell
// in the row after qc_statusTh with "TESTING"
$(qc_statusCell).each(function() {
$(this).replaceWith("TESTING");
});
}
});
如何编辑此代码以循环遍历表中索引相等的每个单元格qc_statusColumnIndex
?
如果你考虑一下,你真的想迭代(使用each
(表格的行,而不是单元格。如果这样做,则可以从每行中获取第 n 个td
元素并应用转换。
$(document).ready(function() {
var $table = $("table.tables.list");
if ($table.length > 0) {
var qc_statusTh = $("th.headersub:contains('qc_status')");
var qc_statusColumnIndex = $(qc_statusTh).index();
var qc_rows = $($table).find('tr');
$(qc_rows).each(function() {
$(this).find('td').eq(qc_statusColumnIndex).replaceWith("TESTING");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tables list">
<thead>
<th class="headersub">qc_example</th>
<th class="headersub">qc_status</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Ok</td>
</tr>
<tr>
<td>2</td>
<td>Ok</td>
</tr>
<tr>
<td>3</td>
<td>Error</td>
</tr>
</tbody>
</table>