繁体   English   中英

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

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

我有一个动态创建的表,如下所示:

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

就像上面的代码注释一样,当用户单击表的第三列中的单元格时,如何获取特定行的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> 

链接到最近的()文档

使用jQuery 最近的()attr()

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

使用类别

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM