gpt4 book ai didi

jquery - 获取 "td"元素的jquery索引

转载 作者:行者123 更新时间:2023-12-03 22:44:11 25 4
gpt4 key购买 nike

我有标记

 <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诀窍是:

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

由于您是在循环内执行此操作,因此更合适的选择是

var answer = $(this).find("input[type='checkbox']:checked").parent().index();

关于jquery - 获取 "td"元素的jquery索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10613873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com