如何使用JQuery在表中获得的位置?
例如:
1,1 2,1 2,1 2,2
我想使用以下function:
$("td").click(function(){ alert(xxxx) })
单击时获取
不带参数调用的index
函数将获得相对于其兄弟节点的位置(无需遍历层次结构)。
$('td').click(function(){ var $this = $(this); var col = $this.index(); var row = $this.closest('tr').index(); alert( [col,row].join(',') ); });
核心/指数
$("td").click(function(){ var column = $(this).parent().children().index(this); var row = $(this).parent().parent().children().index(this.parentNode); alert([column, ',', row].join('')); })
根据这个答案 ,DOM Level 2分别公开了td
和tr
元素的cellIndex
和rowIndex
属性。
让你这样做,这是非常可读的:
$("td").click(function(){ var column = this.cellIndex; var row = $(this).parentNode.rowIndex; alert("[" + column + ", " + row + "]"); });
在jQuery 1.6中:
$(this).prop('cellIndex')
$("td").click(function(e){ alert(e.target.parentElement.rowIndex + " " + e.target.cellIndex) });
tr, td { padding: 0.3rem; border: 1px solid black } table:hover { cursor: pointer; }
0, 0 0, 1 0, 2 1, 0 1, 1 1, 2