2013-09-21 57 views
1

我有一個簡單的HTML代碼:jQuery無法獲得頂級父?

<section class="main"> 
    <div class="container"> 
     <div class="row"> 
      <header class="verticalCenter"> 
      ... 
      </header> 
     </div> 
    </div> 
</section> 

另外,我有這樣的jQuery:

function verticalCenter(el) { 
    el.each(function() { 
     var elHeight = $(this).outerHeight(true), 
      parentHeight = $(this).parent('section').outerHeight(true), 
      marginTop = (parentHeight - elHeight)/2; 

     $(this).css('margin-top',marginTop); 
    }) 
} 

verticalCenter($('.verticalCenter')) 

問題是 - jQuery的沒有看到section.main。我做錯了什麼?

回答

3

你想.closest(),不.parent()

parentHeight = $(this).closest('section').outerHeight(true), 

.parent()功能檢查直接父。有效地傳遞一個選擇符意味着「讓我父母,但只有當父母匹配這個選擇器;否則,給我一個空的列表。」

3

.parent()僅在DOM樹上向上移動一級。在您的代碼中,$(".verticalCenter")沒有任何與選擇器「部分」匹配的直接父節點。

.closest()同時獲得與傳遞的選擇器匹配的最接近的祖先。

$(this).closest('section.main')