在表行中查找td元素位置

时间:2016-03-30 02:44:28

标签: 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 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>

我有一个图像网格,我正在尝试查看网格中的哪些图像已被点击。我试过这个:

$('td img').on('click', function(x){
   console.log("Cell index is: " + x.cellIndex); 
});

但它只记录undefined

5 个答案:

答案 0 :(得分:9)

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

https://api.jquery.com/index/

 function myFunction(x) {
   alert($(x).index());
 }

希望它有所帮助。

答案 1 :(得分:3)

&#13;
&#13;
$('td img').on('click', function(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);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td><img src="1.jpg" /></td>
    <td><img src="2.jpg" /></td>
  </tr>
  <tr>
    <td><img src="1.jpg" /></td>
    <td><img src="2.jpg" /></td>
  </tr>
</table>
&#13;
&#13;
&#13;

答案 2 :(得分:2)

在vanilla 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)
  });
}

onclick事件附加到页面上的每个TD元素。这是Fiddle of it in action,使用jQuery,您只需指定x引用的内容。

$('td').on('click', function(e){
    alert('this.cellIndex: ' + this.cellIndex + '\n$(this),index(): ' + $(this).index());
});

Documentation on event.target

答案 3 :(得分:2)

您只需要在尝试获取索引的元素上调用public class CargoFlight extends Flight { private int passengers = 0; public void setPassengers(int p) { passengers = p; } @Override public boolean fly() { if (passengers <= 0) { throw new IllegalStateException(); // or whichever } return super.fly(); } }

.index()

这是一个小提琴:

https://jsfiddle.net/407u4Lp2/1/

答案 4 :(得分:1)

&#13;
&#13;
$('table tr td').click(function() {

  console.log($(this).index()) //use index() to get the index of clicked td

})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Click to show cellIndex|</td>
    <td>Click to show cellIndex|</td>
    <td>Click to show cellIndex|</td>
    <td>Click to show cellIndex|</td>
  </tr>
</table>
&#13;
&#13;
&#13;

点击一下td并使用.index()获取点击td的索引