簡體   English   中英

當用戶單擊jquery中的特定列表時,如何獲取行號和列號

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

如果用戶單擊html表中的特定列,我如何獲取它的行號和列號。

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

我建議:

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

JS小提琴演示

假設#id是一個td元素:

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

當然,更復雜的表結構需要更復雜的選擇器。 您需要顯示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:

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);
});

小提琴: http : //jsfiddle.net/Varinder/Rr7JS/

請嘗試以下操作:

$("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