jQuery元素索引 [英] jQuery element index
问题描述
我有一个充满表格数据的表.我需要在表中找到一列(单元格)的索引.
I have a table full of tabular data. I need to find the index of a column(cell) in the table.
例如:
<table>
<tr>
<td>Column1</td>
<td>Column2</td>
<td>Column3</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td>foobar</td>
</tr>
</table>
function TestIndexOf(someTD)
{
$(someTD) // what's my column index?
}
推荐答案
$('td').prevAll().length
将为您提供基于0的单元格索引
$('td').prevAll().length
will give you the 0-based index of a cell
或者使用 index()
(可以在其中传递DOM元素或jQuery对象.如果是jQuery对象,则仅使用包装集中的第一个对象)
Alternatively using index()
(can pass a DOM element or a jQuery object in. If jQuery object, only the first object in the wrapped set is used)
var cell = $('td'); // select on cell
cell.parent().index(cell);
如果我没记错的话,index()
将在jQuery 1.4中更容易使用,并且允许您仅对包裹在jQuery对象中的元素调用index()来获取索引,就像这样
If I recall correctly, index()
will be easier to use in jQuery 1.4 and will allow you to simply call index() on the element wrapped in a jQuery object to get the index, like so
$('td').index() // NOTE: This will not work in versions of jQuery less than 1.4
所以对于您的功能
function TestIndexOf(someTD) {
return $(someTD).prevAll().length;
}
这篇关于jQuery元素索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!