我有一张桌子如下:
<table id="testTable" class="mainTable">
<thead>
<tr>
<th>Title</th>
<th>
Select All
<input type="checkbox" id="select_all">
</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td><input type="checkbox" class="checkbox"></td>
</tr>
<tr>
<td>Cell 2</td>
<td><input type="checkbox" class="checkbox"></td>
</tr>
<tr>
<td>Cell 3</td>
<td><input type="checkbox" class="checkbox"></td>
</tr>
<tr>
<td>Cell 4</td>
<td><input type="checkbox" class="checkbox"></td>
</tr>
</tbody>
</table>
目前,我的JS代码将从表中获取所有第一个
td
元素,而不考虑复选框,代码如下:$("#testTable tr").each(function() {
firsttd += $(this).find("td:first").html() + "\n";
});
但是,我需要修改它,以便我的JS代码只获得选中复选框行的第一个
td
元素。 最佳答案
可以直接在选择器上添加条件,如:
$("#testTable :checkbox:checked").each(function() {
firsttd += $(this).closest('tr').find("td:first").html() + "\n";
});
或者,如果您确实需要循环,并且由于您使用的是jQuery,因此可以使用
.is(':checked')
这样的命令:if ( $(this).find(':checkbox').is(':checked') )
{
firsttd += $(this).find("td:first").html() + "\n";
}
希望这有帮助。
var firsttd = "";
$("#testTable :checkbox:checked").each(function() {
firsttd += $(this).closest('tr').find("td:first").html() + "\n";
});
console.log(firsttd);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="testTable" class="mainTable" border=1>
<thead>
<tr>
<th>Title</th>
<th>Select All <input type="checkbox" id="select_all"></th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td><input type="checkbox" class="checkbox" checked></td>
</tr>
<tr>
<td>Cell 2</td>
<td><input type="checkbox" class="checkbox"></td>
</tr>
<tr>
<td>Cell 3</td>
<td><input type="checkbox" class="checkbox" checked></td>
</tr>
<tr>
<td>Cell 4</td>
<td><input type="checkbox" class="checkbox"></td>
</tr>
</tbody>