2009-05-21 61 views
0

我有一個看起來有點像這樣的形式:如何獲得沒有'this'的元素的索引?

<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。我認爲可能有些簡單的我錯過了,但是我的想法在這個問題上留下了一個空白。

回答

5

保持簡單:

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

我就引用自己:「我認爲有可能是一些簡單的我失蹤......」 感謝。 – swilliams 2009-05-21 21:15:16

1
var i = $(this).parents('.contact:first').prevAll('.contract').length 
相關問題