2014-01-17 89 views
0

此代码的工作,但三联.parent()油腻的感觉,我想知道是否有这样做找到家长,jQuery的

注意

的HTML被重复多次的更有效的方法在页面上,所以我必须使用类和以动画只对选定的项目

jQuery的(本)

$('.view').click(function() { 
    $(this).parent().parent().parent().find('.innerContain').animate({ left: '-100%' }, 500); 
}); 

HTML

<div class="mask"> 
    <div class="innerContain"> 
     <!-- Update --> 
     <ul class="updateCSI"> 
      <span class="view">View</span> 
     </ul> 
     <!-- View --> 
     <ul class="viewCSI"> 
      <span class="update">Update</span> 
     </ul> 
    </div> 
</div> 
+0

[如何选择匹配选择器的第一个祖先?](http://stackoverflow.com/questions/2867022/how-to-select-first-ancestor-that-matches-a-selector) –

回答

1

为什么不:

$(this).closest('.innerContain'); 

在这种情况下closest()将帮助你得到与.innerContain类,其祖先的第一个元素当遍历DOM树时,元素为.view

+0

这将无法正常工作 - 它需要$(this) – cyberwombat

+0

我将.view更改为(this),我知道他在说什么,我只需要知道最接近 – user934902

+0

@Yashua好了,修正了:D – Felix

2

我想$(this).closest('.innerContain')也将这样做。

Live demo (click).(我使用.hide()用于演示的缘故。)

+0

@ user934902没问题! – m59