如何获得牢房的位置 [英] How to get a cell's location

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

问题描述

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

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.

推荐答案

使用event对象的target属性可以很容易地做到这一点:

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天全站免登陆