2017-08-13 102 views
2

请参阅fiddle。当我单击单元格时,我可以获取值和列名。我想知道怎样才能得到行列索引呢?以下是js代码,如何通过单击来返回表格单元格的行和列索引

<script type="text/javascript"> 

    $(document).ready(function(){ 
     $('#example tbody').on('click', 'td', function() { 
      alert('Data:'+$(this).html().trim()); 
      alert('Row:'+$(this).parent().find('td').html().trim()); 
      alert('Column:'+$('#example thead tr th').eq($(this).index()).html().trim()); 
     }); 
    }); 

</script> 

回答

2

最好的可能是在这里使用closest

对于组中的每一个元素,获得通过测试元件本身的选择相匹配的第一个元素和遍历DOM树中的祖先。

<script type="text/javascript"> 

    $(document).ready(function(){ 
     $('#example tbody').on('click', 'td', function() { 
      alert('Row ' + $(this).closest("tr").index()); 
      alert('Column ' + $(this).closest("td").index()); 
     }); 
    }); 

</script> 
0

使用本

$(document).ready(function(){ 
    $('#example tbody').on('click', 'td', function() { 

     var column_num = parseInt($(this).index()); 
     alert('column index:'+column_num); 

     var row_num = parseInt($(this).parent().index()); 
     alert('rowindex:'+row_num); 
    }); 
}); 
1

无需jQuery的,你可以用原生JS实现它:

const table = document.querySelector('table'); 
const rows = document.querySelectorAll('tr'); 
const rowsArray = Array.from(rows); 

table.addEventListener('click', (event) => { 
    const rowIndex = rowsArray.findIndex(row => row.contains(event.target)); 
    const columns = Array.from(rowsArray[rowIndex].querySelectorAll('td')); 
    const columnIndex = columns.findIndex(column => column == event.target); 
    console.log(rowIndex, columnIndex) 
}) 
0

指数()可以做的工作。只要找到正确的收集和潮流元素,做 elementCollcetions.index(currentElement)

$(document).ready(function(){ 
 
     $('#example tbody').on('click', 'td', function() { 
 
       
 
\t  alert('ColumnIndex:'+ $(this).parent().find('td').index(this)); 
 
\t  alert('RowIndex:'+ $(this).parent().parent().find('tr').index($(this).parent())); 
 
      
 
     }); 
 
    }); 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="example"><tbody> 
 
<tr><td>11</td><td>12</td></tr> 
 

 
<tr><td>21</td><td>22</td></tr> 
 
</tbody> 
 
</table>

相关问题