如何使用jQuery定位特定表格单元格?
问题描述:
我想使用jQuery将特定表格单元格的#id变成变量,但没有多少运气。任何人都可以提供建议吗?我做了一个小提琴here。如何使用jQuery定位特定表格单元格?
HTML
<input type="button" id="button" value="Click Me" />
<table id="myTable1">
<tbody>
<tr>
<td id="1">
cell 1
</td>
<td id="2">
Get the id of this cell
</td>
<td id="3">
cell 2
</td>
</tr>
</tbody>
</table>
jQuery的
$(document).ready(function() {
$("#button").click(function() {
var td = $(this).closest('table').attr('id'); //find table id
alert(td);
});
});
答
这里的第一个解决方案。如果你想获得的所有的ID从每个细胞。希望能帮助到你!
$(document).ready(function() {
$("#button").click(function() {
var ids = [];
$("tr > td").each(function(index){
ids.push($(this).attr("id"));
});
alert(ids);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="button" id="button" value="Click Me" />
<table id="myTable1">
<tbody>
<tr>
<td id="1">
cell 1
</td>
<td id="2">
Get the id of this cell
</td>
<td id="3">
cell 2
</td>
</tr>
</tbody>
</table>
这里的第二个解决方案,如果你想看到的ID的一个接一个。
$(document).ready(function() {
$("#button").click(function() {
$("tr > td").each(function(index){
alert($(this).attr("id"));
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="button" id="button" value="Click Me" />
<table id="myTable1">
<tbody>
<tr>
<td id="1">
cell 1
</td>
<td id="2">
Get the id of this cell
</td>
<td id="3">
cell 2
</td>
</tr>
</tbody>
</table>
应该如何代码知道哪个小区** **你想要的目标? –
我希望你能帮助我。 – JulianJ
使用'next'而不是''this(this).next('table')。attr('id');' – Azim