如何使用jQuery获取此元素的索引?

ale*_*lex 5 html javascript xhtml jquery

我试图使用jQuery获取元素的索引以发送到PHP脚本.

这是我的XHTML

<form action="/accreditation/questions/" method="post" id="questions-form">
  <fieldset id="question-0">
    <legend>Question</legend>
    <h3>What colour is grass?</h3>    
    <ul>
      <li>
        <input type="radio" name="answer[0]" value="0" id="radio-0-0" />
        <label for="radio-0-0">Green</label>
      </li>
      <li>
        <input type="radio" name="answer[0]" value="1" id="radio-0-1" />
        <label for="radio-0-1">Red</label>
      </li>
      <li>
        <input type="radio" name="answer[0]" value="2" id="radio-0-2" />
        <label for="radio-0-2">Orange</label>
      </li>
    </ul>
  </fieldset>
  <fieldset id="question-1">
    <legend>Question</legend>
    <h3>how old is alex</h3>    
    <ul>
      <li>
        <input type="radio" name="answer[1]" value="0" id="radio-1-0" />
        <label for="radio-1-0">21</label>
      </li>
      <li>
        <input type="radio" name="answer[1]" value="1" id="radio-1-1" />
        <label for="radio-1-1">11</label>
      </li>
      <li>
        <input type="radio" name="answer[1]" value="2" id="radio-1-2" />
        <label for="radio-1-2">23</label>
      </li>
    </ul>
  </fieldset>
</form>
Run Code Online (Sandbox Code Playgroud)

我需要获取fieldset元素的索引.我目前正在使用每个迭代器(我不想改变它,因为它里面有很多其他函数).

$('#questions-form ul li').each(function() {
    qIndex = $('fieldset').index($('fieldset', $(this).parent()))
});
Run Code Online (Sandbox Code Playgroud)

我希望qIndex成为相对于表单的fieldset的索引.例如,在这种情况下,我应该将它等于0和1(尽管会有6个值,因为它循环遍历列表元素).

我已经玩了一段时间,但无法获得正确的索引.我一直没找到(-1).

如果它有帮助,这里是我用来获取列表项相对于它的包含ul元素的索引的代码.

index = $('li', $(this).parent()).index(this);
Run Code Online (Sandbox Code Playgroud)

我的fieldset索引抓取代码有什么问题?

Sco*_*den 16

LI的父UL,不是fieldset.
我想这会qIndex为你做好准备:

qIndex = $('fieldset').index($(this).parents('fieldset'));
Run Code Online (Sandbox Code Playgroud)