jQuery 中的表格行和列号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/788225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Table row and column number in jQuery
提问by Jonas
How do I get the row and column number of the clicked table cell using jQuery, i.e.,
如何使用 jQuery 获取单击的表格单元格的行号和列号,即,
$("td").onClick(function(event){
var row = ...
var col = ...
});
回答by CMS
You can use the Core/indexfunction in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number:
您可以在给定的上下文中使用Core/index函数,例如您可以在其父 TR 中检查 TD 的索引以获取列号,并且您可以检查表上的 TR 索引以获取行号:
$('td').click(function(){
var col = $(this).parent().children().index($(this));
var row = $(this).parent().parent().children().index($(this).parent());
alert('Row: ' + row + ', Column: ' + col);
});
Check a running example here.
在此处检查运行示例。
回答by Phillip Senn
$('td').click(function() {
var myCol = $(this).index();
var $tr = $(this).closest('tr');
var myRow = $tr.index();
});
回答by Louie Santiano
Get COLUMN INDEX on click:
单击获取列索引:
$(this).closest("td").index();
Get ROW INDEX on click:
点击获取 ROW INDEX:
$(this).closest("tr").index();
回答by Samantha Branham
Off the top of my head, one way would be to grab all previous elements and count them.
在我的脑海中,一种方法是获取所有以前的元素并计算它们。
$('td').click(function(){
var colIndex = $(this).prevAll().length;
var rowIndex = $(this).parent('tr').prevAll().length;
});
回答by Chris Brandsma
Can you output that data in the cells as you are creating the table?
您可以在创建表格时在单元格中输出该数据吗?
so your table would look like this:
所以你的桌子看起来像这样:
<table>
<thead>...</thead>
<tbody>
<tr><td data-row='1' data-column='1'>value</td>
<td data-row='1' data-column='2'>value</td>
<td data-row='1' data-column='3'>value</td></tr>
<tbody>
</table>
then it would be a simple matter
那么这将是一件简单的事情
$("td").click(function(event) {
var row = $(this).attr("data-row");
var col = $(this).attr("data-col");
}
回答by mkoryak
its better to bind a click handler to the entire table and then use event.target to get the clicked TD. Thats all i can add to this as its 1:20am
最好将单击处理程序绑定到整个表,然后使用 event.target 来获取单击的 TD。这就是我可以添加的所有内容,因为它是凌晨 1 点 20 分