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

swi*_*ams 0 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>
Run Code Online (Sandbox Code Playgroud)

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

var i = $(this).parents('.contact').index(this);
Run Code Online (Sandbox Code Playgroud)

不幸的是,this在这种情况下,运营商指的form是正在提交的运营商.我想可能有一些我想念的简单,但我的思绪在这一点上画了一个空白.

Pao*_*ino 5

把事情简单化:

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