使用jQuery在td中单击获取表id

问题描述 投票:6回答:4

我在表头中有一个包含几个输入字段的tr。

有没有办法通过点击其中一个输入字段我可以得到父表的ID?

我的tr看起来像这样:

<table id="tableID">
    <thead>
        <tr>
            <th><input type="text" name="input1" id="input1" /></th>
            <th><input type="text" name="input2" id="input2" /></th>
            <th><input type="text" name="input3" id="input3" /></th>
        </tr>
    </thead>
    <tbody>
        // ...
    </tbody>
</table>
jquery identifier
4个回答
31
投票

在点击处理程序中,您可以使用.closest()

$(this).closest('table').attr('id')


2
投票
$("#tableID").on("click","input[type='text']",function(){

$(this).closest('table').attr('id');

});

参考closest()


1
投票

您应该委派事件以避免多个处理程序,然后使用delegateTarget来定位当前的TABLE:

$('table').on('click', 'input', function (e) {
    alert(e.delegateTarget.id);
});

1
投票

您可以使用

$('#tdId').click(function(){
    $(this).parents('table').attr('id');
});

有用。

© www.soinside.com 2019 - 2024. All rights reserved.