0

I have a table like this, and I need to get a row index value when clicking on a particular cell in a row. I don't need to get any values when clicking on rest of the cells.

<table>
   <tr>
      <td>1</td><td>1</td><td>1</td>
   </tr>
   <tr>
      <td>2</td><td>2</td><td>2</td>
   </tr>
      <td>3</td><td>3</td><td>3</td>
   </tr>
</table>

Here is my jQuery code goes. I am getting row index value perfectly

$(function(){

    $("table tr").click(function(){
    console.log($(this).index());
});
});

But I need like when clicking on particular cell only. Here I used third cell.

//$("table tr").find('td').eq(2).click(function() {
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
htoniv
  • 1,658
  • 21
  • 40

2 Answers2

0

You can use closest('tr').

$(function(){

    $("table tr td").click(function(){
    console.log($(this).closest('tr').index());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
   <tr>
      <td>1</td><td>1</td><td>1</td>
   </tr>
   <tr>
      <td>2</td><td>2</td><td>2</td>
   </tr>
      <td>3</td><td>3</td><td>3</td>
   </tr>
</table>
tkay
  • 1,716
  • 14
  • 18
0
    <table>
        <tr>
            <td>1</td><td>1</td><td>1</td>
        </tr>
        <tr>
            <td>2</td><td>2</td><td>2</td>
        </tr>
        <tr>
            <td>3</td><td>3</td><td>3</td>
        </tr>
    </table>


     $(function(){

         $("table tr").each(function(){
            $(this).find("td").eq(2).click(function(){
                console.log($(this).text());
            });

         });
     });

use this code will help you

http://jsfiddle.net/sc6Ld40v/

Vishwajeet Bose
  • 430
  • 3
  • 12