简体   繁体   中英

Get column header and row header on cell click

I already have the function working on selecting a cell, using this:

$('td').click(function(){
    //do things here
}

I want it get the text from the header of the column (this is within thead and then it's own th tag), and also get the row header, this is the left most column on the table and is also denoted under a th tag.

HTML:

<table>
<thead>
<tr>
    <th>Day/Time</th>
    <th>10:00</th>
    <th>11:00</th>
    <th>12:00</th>
</tr>
<tbody>
<tr>
    <th>Monday</th>
    <td>Cell data</td>
    <td>Cell data</td>
    <td>Cell data</td>
</tr>
<tr>
    <th>Tuesday</th>
    <td>Cell data</td>
    <td>Cell data</td>
    <td>Cell data</td>
</tr>
<tr>
    <th>Wednesday</th>
    <td>Cell data</td>
    <td>Cell data</td>
    <td>Cell data</td>
</tr>
</tbody>
</table>

Here we go, exotic blend of jQuery and pure JS:

$('table').on('click', 'td', function(e) {  
    var time = e.delegateTarget.tHead.rows[0].cells[this.cellIndex],
        day  = this.parentNode.cells[0];

    alert([$(day).text(), $(time).text()]);
});

Demo: http://jsfiddle.net/fv3gZ/

I would recommend to delegate click events to the table, instead of binding click on each td , it would increase performance.

As your html structure if you wanted to get header of corresponding cell you can use siblings Try this:

demo : http://jsfiddle.net/qsDn5/29/

  $('td').on('click',function() {
       var text = $( this ).siblings('th').text();
        alert(text);
    });

You can try this:

var td = document.getElementsByTagName("td"),
titles = document.getElementsByTagName("th")
for (var i = 0; i < td.length; i++) {
td[i].addEventListener("click", function () {
alert(titles[this.cellIndex].innerHTML);
}, false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM