简体   繁体   中英

How to check in jQuery datatable the clicked row and column?

Use case: user clicks on a datatable cell. Depending on the row and column of that cell certain action should be executed.

How can I check whether that doesn't click on a certain column and if he does not click on that column, then I would retrieve information from the row he clicked on and allow him to execute an action based on that information.

I did it like this and it works:

  var validColumn = false;
  $('#fooTable tbody').on( 'click', 'td', function () {
    validColumn = $('#fooTable').DataTable().cell(this).index().column !== 5;
  });
  $('#fooTable tbody').on('click', 'tr', function () {
    if (validColumn) {
       //do stuff
    }
  });

But I feel there is a more elegant approach.

First set an aria to the td to identify the position, something like Table wiht 6 columns so

<tr aria-number="1">
    <td aria-number="1">
    <td aria-number="2">
    <td aria-number="3">
    <td aria-number="4">
    <td aria-number="5">
    <td aria-number="6">
</tr>

Same for tr, think is easy way to do

Use jQuery function .parent(), sending $(this), so.

var td = $(this).parent();//If the item clicked is something inside of td
var tr = $(this).parent().parent();//To select the tr where was clicked

And call the aria with

if(td.attr('aria-number') == 6){ //do something; }

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