jQuery 获取“td”元素的jquery索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10613873/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:36:04  来源:igfitidea点击:

get the jquery index of "td" element

jquery

提问by Paras

I have markup

我有标记

 <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>???

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.

在这里,我想获取选中复选框的特定 td 的索引。例如,这里应该是 1。但我每次都得到 0,这似乎是该行的索引。这是我使用的 jquery 代码。

   var answers = $('table tr.ans');
 $.each(answers, function () {
  var answer = $(this).find("input[type='checkbox']:checked").index(); 
    alert(answer);                   
  });?

and here is the fiddleHow do I get the index of the particular td? Thanks

这是小提琴如何获得特定 td 的索引?谢谢

回答by Jon

You can do it with

你可以用

$("table tr.ans input[type='checkbox']:checked").parent().index();

You simply need to navigate from the checkbox back up to the <td>, at which point stright calling .indexdoes the trick:

您只需要从复选框导航回到<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.

如果没有参数传递给 .index() 方法,则返回值是一个整数,指示 jQuery 对象中第一个元素相对于其兄弟元素的位置。

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();

回答by ?yvind Br?then

Change the line to this:

将行更改为:

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

This will give you the index of the tdthat is the parent of the input you have selected in your jquery selector.

这将为您提供您td在 jquery 选择器中选择的输入的父项的索引。