如何获取单元格的位置 [英] How to get a cell's location

查看:132
本文介绍了如何获取单元格的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个管理非常大的表的脚本。当用户点击表格单元格时,我想知道他们点击了哪个单元格。
例如

I'm writing a script which manages a very large table. When a user clicks a table cell, I would like to know which cell they clicked. e.g

--------------
|     |      |
|     | Click|
--------------

应该给我(1,1)的单元格引用。

should give me a cell reference of (1, 1).

任何方式我都可以用javascript做到这一点。它运行的页面使用jquery用于其他目的,因此任何基于jquery的解决方案都是好的。

Any way I could do this with javascript. The page it's running on uses jquery for other purposes, so any jquery based solutions are good aswell.

编辑:为了澄清,左上角的单元格是(0,0) 。出于性能原因,事件需要绑定到,而不是tds。

To clarify, the top left cell is (0, 0). For performance reasons, the event needs to bound to the table, not the tds.

推荐答案

使用事件对象的目标属性非常容易地完成:

This is done very easily using the target property of the event object:

$('#mytable').click(function(e) {
    var tr = $(e.target).parent('tr');
    var x = $('tr', this).index(tr);
    var y = tr.children('td').index($(e.target));
    alert(x + ',' + y);
});

这种方法允许你只将1个事件处理程序绑定到整个表,然后找出哪个表格单元格被点击了。这被称为事件委托,并且在正确的情况下可以更有效,并且这符合要求。使用此功能可以避免将事件绑定到每个< td> ,并且不需要硬编码坐标。因此,如果您的表格如下所示:

This approach allows you to only bind 1 event handler to the entire table and then figure out which table cell was clicked. This is known as event delegation and can be much more efficient in the right situation, and this one fits the bill. Using this you avoid binding an event to each <td>, and it does not require hard-coding coordinates. So, if your table looks like this:

<table id='mytable'>
    <tr>
      <td>hi</td>
      <td>heya</td>
    </tr>
    <tr>
      <td>boo</td>
      <td>weee</td>
    </tr>
</table>

它会在点击时提醒坐标。你可以做任何事情。 :)

It will alert the coordinates on click. You can do whatever with that. :)

如果您发现性能太慢(取决于您的桌子有多大),那么您将不得不求助于硬编码或两者的组合,可能只是硬编码< tr> 索引,因为这是最慢的,然后得到< td> 动态索引。最后,如果所有这些坐标业务完全没有必要,而您真正想要的是对点击的< td> 的引用,您只需执行此操作:

If you find performance to be too slow (depending on just how large your table is) you would then have to resort to hardcoding or a combination of the two, maybe only hard coding the <tr> index, as that would be the slowest to get, and then getting the <td> index dynamically. Finally, if all this coordinate business is completely unnecessary and what you really just wanted was a reference to the clicked <td>, you would just do this:

$('#mytable').click(function(e) {
    var td = $(e.target);
    // go crazy
});

这篇关于如何获取单元格的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆