我的表格看起来像这样:
<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
。我觉得可能有一些我想念的简单,但我的思绪在这一点上留下了空白。
答案 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