2012-05-12 59 views
0

可能重复:
Detecting closest or parent div找到元素的父与jQuery

我需要有关查找使用jQuery元素一些帮助。作为主题提示,我需要找到给定元素的容器。我已经有了一个类似的代码;

$('.cancel_button').bind "click", (event) -> 
    element = $(this.parentElement) 
    ... 
    ... 

但是,它对我来说似乎非常丑陋。取消button位于section元素中。我不知道是否有可能做这样的事情

$(this).containerElement('section') 
+0

看起来很丑陋,因为取消按钮可能存在于更深层次结构中。 –

+2

从头到尾阅读[jQuery API](http://api.jquery.com)非常值得花费一两个小时的时间。这真的只需要很长时间,你会在一个星期内恢复这些时间。我向你保证。 –

回答

5

你可能会寻找parentclosest

$(this).parent() 

// or 

$(this).closest('section') 

你甚至可能会希望将它们组合,因为closest将返回当前元素如果匹配。所以,如果你有一个div这是一个section,这是内div内:

<div id="outer"> 
    <section> 
     <div id="inner">....</div> 
    </section> 
</div> 

...你想获得outer当一个事件发生inner,它会是:

$(this).parent().closest('div'); 

但是当你开始的元素与选择器不匹配时,你不需要它。

+2

+1最有可能'最接近'。 –

+0

感谢您的详细解答。我认为.closest是我想要的:) –

1
$(this).parent(); // get parent of current object 
$(this).closest('.class'); // get closest parent that have class="class" 
$(this).closest('section') // get closest parent that is section element