我有一个动态创建的表格:
<div id="gameListDiv">
<table id="gameListTable">
<tr id="1">
<td>A</td>
<td>B</td>
<td class="tpButton">C</td>
</tr>
<tr id="2">
<td>D</td>
<td>E</td>
<td class="tpButton">F</td>
</tr>
</table>
</div>
我有一个听众:
$('#gameListDiv').on('click','.tpButton', function(toggleThisTP) {
// If user clicks C, return the row ID of '1'
// if user clicks F, return the row ID Of '2'
});
与上面的代码注释一样,当用户单击表格第3列中的单元格时,如何获取特定行的ID标记的值?
答案 0 :(得分:8)
这应该有效:
$('#gameListDiv').on('click','.tpButton', function() {
var id = jQuery(this).closest('tr').attr('id');
alert(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="gameListDiv">
<table id="gameListTable">
<tr id="1">
<td>A</td>
<td>B</td>
<td class="tpButton">C</td>
</tr>
<tr id="2">
<td>D</td>
<td>E</td>
<td class="tpButton">F</td>
</tr>
</table>
</div>
答案 1 :(得分:2)
$('#gameListDiv').on('click','.tpButton', function(toggleThisTP) {
var row = $(this).closest('tr');
var id = row.attr('id');
});
答案 2 :(得分:1)
使用班级
<div id="gameListDiv">
<table id="gameListTable">
<tr class="gamelist" id="1">
<td>A</td>
<td>B</td>
<td class="tpButton">C</td>
</tr>
<tr class="gamelist" id="2">
<td>D</td>
<td>E</td>
<td class="tpButton">F</td>
</tr>
</table>
</div>
Jquery的
$(".gamelist").click(function(){
var id = $(this).attr('id');
alert(id);
});