[英]How can I create a table that appends a column every time a user clicks on it
[英]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);
});
請嘗試以下操作:
$("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.