简体   繁体   中英

How can I get the row and column number when the user clicks in a particular column table in jquery

If the user clicks a particular column in a html table, how can I get the row and column number of it.

  $("table #id").click(function()
  {
          //get row and column num
  }); 

I'd suggest:

$('td').click(function (){
    var cell = this,
          col = cell.cellIndex + 1,
          row = cell.parentNode.rowIndex + 1;
    console.log('Row: '  + row + ', column: ' + col)
});

JS Fiddle demo .

Assuming that #id is a td element:

var myRow = $(this).parent('tr').index();
var myCol = $(this).index();

Of course, more complex table structures require more complex selectors. You'd need to show your HTML for further assistance.

This should be pretty straight forward:

HTML

<p class="result"></p>
<table>
    <tr>
        <td>row 1 - cell 1</td>
        <td>row 1 - cell 2</td>
        <td>row 2 - cell 3</td>
    </tr>
    <tr>
        <td>row 2 - cell 1</td>
        <td>row 2 - cell 2</td>
        <td>row 2 - cell 3</td>
    </tr>
    <tr>
        <td>row 3 - cell 1</td>
        <td>row 3 - cell 2</td>
        <td>row 3 - cell 3</td>
    </tr>
</table>

JS:

var $result = $(".result");
$("table").on("click", "td", function(e) {
    var $tableCell = $(this);
    var tableCellNumber = $tableCell.index() + 1;
    var tableRowNumber = $tableCell.parent().index() + 1;

    var result = "row number: " + tableRowNumber + ", cell number: " + tableCellNumber;

    $result.text(result);
});

Fiddle: http://jsfiddle.net/Varinder/Rr7JS/

Try the following:

$("table tr td").click(function() {
    var rowNo = ($(this).parent().index() + 1);
    var cellNo = ($(this).index() + 1);
    alert("rowNo=" + rowNo + "  ||  cellNo=" + cellNo);
});

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