admin管理员组

文章数量:1287577

I have a dynamically created table as:

<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>

I have a listener:

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

As in the code ments just above, how to I get the value if the ID tag of the specific row when the user clicks a cell in the 3rd column of the table?

I have a dynamically created table as:

<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>

I have a listener:

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

As in the code ments just above, how to I get the value if the ID tag of the specific row when the user clicks a cell in the 3rd column of the table?

Share Improve this question asked Jun 11, 2015 at 14:18 Dan ADan A 1032 silver badges10 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

This should work:

$('#gameListDiv').on('click','.tpButton', function() {
    var id = jQuery(this).closest('tr').attr('id');
    alert(id);
});
<script src="https://ajax.googleapis./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

Use jQuery closest() and attr()

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

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

本文标签: javascriptHow to get the Value of an ID from a TR of a Clicked TD ElementStack Overflow