我有一个像这样的link表。
我怎么知道我点击的td(输入)是第一行还是最后一行?
我怎么知道我单击的td的列索引和td的行索引?
我知道我可以使用$(this)
,但怎么办?
$("#table_reach_condition_appoint tbody td").click(function(){
//$(this)
})
答案 0 :(得分:1)
这是一个示例,您可以如何做。 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>
答案 1 :(得分:0)
$("#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开始。
答案 2 :(得分: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);
});