如何从单击的 TD 元素的 TR 中获取 ID 的值

How to get the Value of an ID from a TR of a Clicked TD Element

我有一个动态创建的 table 作为:

<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'
});

如上面的代码注释,当用户单击 table 的第 3 列中的单元格时,如何获取特定行的 ID 标记的值?

使用jQueryclosest() and attr()

$('#gameListDiv').on('click','.tpButton', function(toggleThisTP) {
    var row = $(this).closest('tr');
    var id = row.attr('id');
});

这应该有效:

$('#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>

Link to closest() documentation

使用Class

<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);
});