Javascript 查找表行中的td元素位置

Javascript 查找表行中的td元素位置,javascript,jquery,html,Javascript,Jquery,Html,如何在表行中查找td元素的位置?我已经看到了这段代码的建议,但是有没有办法让每个td标记都包含onclick事件呢 <table> <tr> <td onclick="myFunction(this)">Click to show cellIndex</td> <td onclick="myFunction(this)">Click to show cellIndex</td> <td on

如何在表行中查找td元素的位置?我已经看到了这段代码的建议,但是有没有办法让每个td标记都包含onclick事件呢

<table>
  <tr>
    <td onclick="myFunction(this)">Click to show cellIndex</td>
    <td onclick="myFunction(this)">Click to show cellIndex</td>
    <td onclick="myFunction(this)">Click to show cellIndex</td>
    <td onclick="myFunction(this)">Click to show cellIndex</td>
 </tr>
</table>

<script>
 function myFunction(x) {
   alert("Cell index is: " + x.cellIndex);
}
</script>
但它只是记录未定义的

$('table tr td')。单击(函数(){
console.log($(this.index())//使用index()获取单击的td的索引
})

单击以显示cellIndex|
单击以显示cellIndex|
单击以显示cellIndex|
单击以显示cellIndex|

在香草JavaScript中,您可以这样处理:

var tds = document.querySelectorAll('td');
for(var i = 0, len = tds.length; i < len; i++) {
    tds[i].addEventListener('click', function(e){
    var td = this || (e || event).target;
        alert(td.cellIndex)
  });
}

您可以在jquery中使用$.index()函数来获取对象的索引


希望能有所帮助。

您只需对试图获取其索引的元素调用
.index()

$('td img').click(function(){
    var index = $(this).parent().index();
});
这是一把小提琴:

$('td img')。在('click',函数(e)上{
var td=$(this.parent();
var tr=td.parent();
var children=tr.children().length;
var tdIndex=td.index()+1;
var trIndex=tr.index();
console.log((trIndex*children)+tdIndex);
});


如果我有一个大网格,比如8 x 8,当我单击第二行的第一个图像时,索引是否会在零处重新开始?是的,但我只是编辑了我的代码片段以满足您的请求。
$('td').on('click', function(e){
    alert('this.cellIndex: ' + this.cellIndex + '\n$(this),index(): ' + $(this).index());
});
 function myFunction(x) {
   alert($(x).index());
 }
$('td img').click(function(){
    var index = $(this).parent().index();
});