我有标记
<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 代码。
var answers = $('table tr.ans');
$.each(answers, function () {
var answer = $(this).find("input[type='checkbox']:checked").index();
alert(answer);
});
这是fiddle如何获取特定 td 的索引?
谢谢
你可以这样做
$("table tr.ans input[type='checkbox']:checked").parent().index();
您只需从复选框导航回到<td>
,此时直接调用.index
诀窍是:
如果没有参数传递给 .index() 方法,则返回值为
一个整数,指示第一个元素在
jQuery 对象相对于其同级元素。
查看实际效果.
由于您是在循环内执行此操作,因此更合适的选择是
var answer = $(this).find("input[type='checkbox']:checked").parent().index();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)