如何获取没有'this'的元素的索引?

时间:2009-05-21 21:10:36

标签: javascript jquery

我的表格看起来像这样:

<div>
    <div class="contact">
        <h1>Person's name</h1>
        <!-- more stuff goes here -->
        <form method="post" action="myurl">
            <input type="submit" value="go" />
        </form>
    </div>
    <div class="contact">
        <h1>Another name</h1>
        <!-- more stuff goes here -->
        <form method="post" action="myOtherUrl">
            <input type="submit" value="go" />
        </form>
    </div>
</div>

我正在使用jQuery来捕获表单的submit事件,并且需要获取包含提交它的按钮的div的索引。通常我会像这样使用jQuery的index()函数:

var i = $(this).parents('.contact').index(this);

不幸的是,在这种情况下,this运算符引用了正在提交的form。我觉得可能有一些我想念的简单,但我的思绪在这一点上留下了空白。

2 个答案:

答案 0 :(得分:5)

保持简单:

var parent = $(this).closest('div.contact'); // get containing DIV
var i = $('div.contact').index(parent); // get index relative to the rest

答案 1 :(得分:1)

var i = $(this).parents('.contact:first').prevAll('.contract').length