Pregunta
Cuando hago clic en la fila del encabezado de la tabla, me gustaría una función genérica para obtener la id del elemento <th> en el que se hizo clic, por lo que no tengo que crear una función separada para cada elemento del encabezado.
Estoy usando jQuery y tengo el siguiente código:
HTML
<div id="title"> <table class="policies sortable"> <thead id="h-th"> <tr id="h-tr"> <th width="3%" id="h-client">Client</th> <th width="7%" id="h-company-code">Company Code</th> <th width="9%" id="h-unique-reference">Unique Reference</th> <th width="8%" id="h-doc-date">Document Date</th> <th width="8%" id="h-post-date">Posting Date</th> <th width="7%" id="h-doc-type">Document Type</th> <th width="5%" id="h-trip-id">Trip Id</th> <th width="7%" id="h-ticket-no">Ticket Number</th> <th width="6%" id="h-calc-tax">Calculate Tax</th> <th width="15%" id="h-passenger-name">Passenger Name</th> <th width="4%" id="h-error">Valid</th> <th width="4%" id="h-processed">Processed</th> <th width="4%" id="h-payment">Payment</th> <th width="11%" id="h-updated">Updated</th> </tr> </thead> </table> </div>JavaScript
$("#h-tr").click(function(item) { console.log(item); // get the id of the clicked <th> });si incluye el th en el selector, puede acceder a la identificación usando $(this)
$("#h-tr th").click(function(item) { console.log($(this).prop('id')); });Puede llamar a
querySelectorAll()en todosthelementos y usar un bucle para iterar y los atributos de console.logconsole.log()una vez que el elemento en el que se hizo clic activa EventListener.
document.querySelectorAll('th').forEach(element => { element.addEventListener('click', () => { console.log(element.getAttribute('id')) }) }) th{cursor:pointer} <div id="title"> <table class="policies sortable"> <thead id="h-th"> <tr id="h-tr"> <th width="3%" id="h-client">Client</th> <th width="7%" id="h-company-code">Company Code</th> <th width="9%" id="h-unique-reference">Unique Reference</th> <th width="8%" id="h-doc-date">Document Date</th> <th width="8%" id="h-post-date">Posting Date</th> <th width="7%" id="h-doc-type">Document Type</th> <th width="5%" id="h-trip-id">Trip Id</th> <th width="7%" id="h-ticket-no">Ticket Number</th> <th width="6%" id="h-calc-tax">Calculate Tax</th> <th width="15%" id="h-passenger-name">Passenger Name</th> <th width="4%" id="h-error">Valid</th> <th width="4%" id="h-processed">Processed</th> <th width="4%" id="h-payment">Payment</th> <th width="11%" id="h-updated">Updated</th> </tr> </thead> </table> </div>