簡體   English   中英

jQuery如何判斷我單擊的td是第一行還是最后一行,以及行索引和列索引?

[英]Jquery how to judge the td I clicked is the first row or last row,and row index and column index?

我有一個像這樣的鏈接表。

在此處輸入圖片說明

我如何知道我單擊的td(輸入)是第一行還是最后一行?

我怎么知道單擊的td的列索引和td的行索引?

我知道我可以使用$(this) ,但是怎么辦?

$("#table_reach_condition_appoint tbody td").click(function(){
    //$(this)
})

這是一個示例,您可以如何做。 index()返回所選元素當前位置的索引。 它從索引0開始。因此,我們需要在結果中加上+1 ,以獲得正確的行/列號。

 $(function(){ $('td').on('click', function(){ var columnNumber = $(this).index() + 1; // add 1 because index starts with 0 var rowNumber = $(this).parent('tr').index() + 1; //Check if the culculated row number is 1 firstcolumn = (columnNumber === 1); firstRow = (rowNumber === 1); //Compare the clicked element with the last element using jQuery's is() function. lastRow = $(this).parent('tr').is(':last-child'); lastColumn = $(this).is(':last-child'); console.log('clicked on: ' + $(this).text()); console.log('row: ' + rowNumber); console.log('column: ' + columnNumber); if(firstcolumn) { console.log('firstColumn'); } if(firstRow) { console.log('firstRow'); } if(lastRow) { console.log('lastRow'); } if(lastColumn) { console.log('lastColumn'); } }) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>1A</td> <td>2A</td> <td>3A</td> <td>4A</td> </tr> <tr> <td>1B</td> <td>2B</td> <td>3B</td> <td>4B</td> </tr> </table> 

$("#table_reach_condition_appoint tbody td").each(function() {
  $(this).on('click', function() {
     var row = $(this).parent('tr').index(),
             column = $(this).index();
     console.log(row, column);
  });
})

除非另有說明,否則行和列將從0開始。

$("#table_reach_condition_appoint tbody td").click(function(){
    var tbl_row_count = $('#table_reach_condition_appoint>tbody>tr').length;
    var col_no = parseInt($(this).index())+1;
    var row_no = parseInt($(this).closest('tr').index())+1;
    if(row_no == 1)
    {
      alert('first row');
    }
    if(row_no == tbl_row_count)
    {
      alert('last row');
    }
   alert('You clicked row no'+row_no+' col no'+col_no);    
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM