简体   繁体   English

当用户单击jquery中的特定列表时,如何获取行号和列号

[英]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. 如果用户单击html表中的特定列,我如何获取它的行号和列号。

  $("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 . JS小提琴演示

Assuming that #id is a td element: 假设#id是一个td元素:

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. 您需要显示HTML以获取更多帮助。

This should be pretty straight forward: 这应该很简单:

HTML 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: 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/ 小提琴: 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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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