У меня есть таблица, в которой ячейки имеют зону с кликами. Когда вы нажимаете на эту область, мне нужно получить индекс родительской ячейки среди своих братьев и сестер.
Похоже, что индексная функция jQuery должна работать независимо от переданного параметра, являющегося объектом jQuery или объектом DOM, но ни один из них не возвращает ожидаемый результат в моем примере.
Любые идеи, что мне здесь не хватает?
Это мой пример:
<table>
<tbody>
<tr>
<td><span class="a">Apricot</span></td>
<td><span class="b">Banana</span></td>
<td><span class="c">Cherry</span></td>
</tr>
</tbody>
</table>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"/></script>
<script>
$('span').click(function(){
var jq_closestCell = $(this).closest('.td');
var dom_closestCell = jq_closestCell[0];
var jq_arrayCells = $('table tr td');
var dom_arrayCells = jq_arrayCells[0];
// This returns -1:
console.log( jq_closestCell.index(dom_arrayCells) );
// This returns -1:
console.log( jq_closestCell.index(jq_arrayCells) );
// Just for completeness, these obviously return
// an error ("Uncaught TypeError: Cannot call method 'index' of undefined")
console.log( dom_closestCell.index(dom_arrayCells) );
console.log( dom_closestCell.index(jq_arrayCells) );
});
</script>
Если вам нужен индекс td
var tdIndex = $(this).closest("td").index();
Или tr
var trIndex = $(this).closest("tr").index();
Сценарий: http://jsfiddle.net/YBp8H/
Вам просто нужно:
$('span').click(function () {
var jq_closestCellIndex = $(this).closest('td').index();
console.log(jq_closestCellIndex );
});
closest('.td')
а неclosest('td')