Par exemple:
1,1 2,1 2,1 2,2
Je veux utiliser la fonction suivante:
$("td").click(function(){ alert(xxxx) })
pour obtenir la position de
La fonction d’ index
appelée sans paramètre obtiendra la position par rapport à ses frères (pas besoin de traverser la hiérarchie).
$('td').click(function(){ var $this = $(this); var col = $this.index(); var row = $this.closest('tr').index(); alert( [col,row].join(',') ); });
Noyau / index
$("td").click(function(){ var column = $(this).parent().children().index(this); var row = $(this).parent().parent().children().index(this.parentNode); alert([column, ',', row].join('')); })
Selon cette réponse , DOM niveau 2 expose les propriétés cellIndex
et rowIndex
des éléments td
et tr
, respectivement.
Vous permet de faire ceci, ce qui est assez lisible:
$("td").click(function(){ var column = this.cellIndex; var row = $(this).parentNode.rowIndex; alert("[" + column + ", " + row + "]"); });
Dans 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