得到"td"的jquery索引.元素 [英] get the jquery index of "td" element
问题描述
我有标记
<table>
<tr id="1">
<td colspan="4">
<p class="que">
1. Who are you?</p>
</td>
</tr>
<tr class="ans">
<td>
<input type="checkbox" />Student
</td>
<td>
<input type="checkbox" checked="true" />Developer
</td>
<td>
<input type="checkbox" />Other
</td>
<td>
<input type="text" />
</td>
</tr>
</table>
在这里,我想获取选中其复选框的特定td的索引.例如,这里应该是1.但是我每次都得到0,这看起来像是行的索引. 这是我使用过的jQuery代码.
Here I want to get the index of the particular td which has its checkbox checked. For example here it should be 1. But I m getting 0 eachtime which seems like the index of the row. Here is the jquery code I have used.
var answers = $('table tr.ans');
$.each(answers, function () {
var answer = $(this).find("input[type='checkbox']:checked").index();
alert(answer);
});
这是小提琴 如何获取特定td的索引? 谢谢
and here is the fiddle How do I get the index of the particular td? Thanks
推荐答案
您可以使用
$("table tr.ans input[type='checkbox']:checked").parent().index();
您只需要从复选框导航回到<td>
,这时直接调用.index
即可达到目的:
You simply need to navigate from the checkbox back up to the <td>
, at which point stright calling .index
does the trick:
如果没有参数传递给.index()方法,则返回值为 一个整数,指示第一个元素在 相对于其同级元素的jQuery对象.
If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
查看实际效果 .
See it in action.
由于您是在循环中执行此操作,因此更加合适
Since you are doing this inside a loop, a more proper fit would be
var answer = $(this).find("input[type='checkbox']:checked").parent().index();
这篇关于得到"td"的jquery索引.元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!