Get table id by click in td using jQuery

梦想与她 提交于 2019-12-01 02:47:03

问题


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

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

My tr looks like this:

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

回答1:


In the click handler you can use .closest()

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




回答2:


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

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

});

reference closest()




回答3:


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

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



回答4:


You can use

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

it works.



来源:https://stackoverflow.com/questions/20175970/get-table-id-by-click-in-td-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!