If a table is defined so:
<colgroup>
<col style="width:100px;">
<col style="width:100px;">
</colgroup>
<thead>
<th class="foo" data-info="zipcode10023">
<th class="foo" data-info="zipcode60602">
</thead>
such that the value in custom attribute data-info is unique, when a cell in the table has been clicked, what is the most efficient way to determine which column has been clicked (i.e. in order to get the data-info value, e.g. “zipcode60606”) ?
EDIT: there may be invisible columns to the left of the clicked-on cell.
Assuming that the click is detected on a cell:
JS Fiddle demo using:
$('thead th').eq(col).attr('data-info').JS Fiddle demo using:
$('thead th').eq($(this).index()).attr('data-info').JS Fiddle demo using:
$('thead th').eq($(this).index()).data('info').You could, of course, place the event-handler on an ancestor element, such as the
tr, with either:JS Fiddle demo.
(Note that, ordinarily,
event.targetisn’t necessarily cross-browser compatible, and Internet Explorer may require (outside of jQuery) an alternative:window.event.srcElement, however jQuery normalizes the events, so that not only will IE read/’understand’ theevent(and not requirewindow.eventinstead) but it will also have access to the normalzedevent.target.)Or, to use enough jQuery:
JS Fiddle demo.
In much the same way the
clickcan also be bound to thetableelement:JS Fiddle demo.
References:
attr().click().data().eq().index().eventobject.on().