使用 jQuery 通过在 td 中单击来获取表 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20175970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:01:17  来源:igfitidea点击:

Get table id by click in td using jQuery

jqueryidentifier

提问by user2571510

I have a tr in a table header that contains several input fields.

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

Is there a way that by click on one of these input fields I can get the id of the parent table ?

有没有办法通过单击这些输入字段之一来获取父表的 ID?

My tr looks like this:

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

回答by Arun P Johny

In the click handler you can use .closest()

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

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

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

回答by Rituraj ratan

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

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

});

reference closest()

参考最近()

回答by Meer

You can use

您可以使用

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

it works.

有用。

回答by A. Wolff

You should delegate event to avoid multiple handlers, and then use delegateTargetto target current TABLE:

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

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