2016-10-17 2 views
1

이것은 아마도 매우 쉬운 방법 일 수 있습니다. 그러나 나는 그것을 파악할 수 없었습니다.현재 div 외부의 div 안에있는 액세스 요소

내 접근 방식은 현재 "항목"의 "img-preview"내에있는 "expanded-image"클래스를 가진 모든 요소를 ​​가져 오는 것입니다.

내 HTML입니다 :

<div class="entry"> 
<div class="img-preview"> 
    <img> 
    <img class="expanded-image" style="display:none;"> 
</div> 

<div class="content"> 
    [..] 
    [..] 
    <span class="more-text"></span> 
    [..] 
    [..] 
</div> 
</div> 

그리고 이것은 내가 함께 일하는 JS입니다 : 당신이 click() 이벤트 핸들러를 적용 할 수 있습니다 당신이 전혀 each() 필요하지 않습니다 첫째

$('.content').each(function(event) { 

    $(this).find('span.more-text').click(function(event) { 

     // TODO 

    }); 
}); 

답변

2

단일 선택기 내의 모든 요소에 적용됩니다.

closest()을 사용하여 클릭 한 .more-text에 가장 가까운 부모 .entry 요소를 찾을 수 있습니다. 거기에서 find() 모든 .expanded-image 요소 수 있습니다. 이 시도 : closest, prevfind

$('span.more-text').click(function(event) { 
    $(this).closest('.content').prev().find('.expanded-image'); 
    }); 
1
$('.content').each(function(event) { 
    var $content = $(this); 

    $(this).find('span.more-text').click(function(event) { 

     $content.parent().find('.expanded-image'); // there you go 

    }); 
}); 
1

사용 O 조합을 당신은 선택에 주어진 부모를 찾을까지 거품에 closest()를 사용할 수 있습니다. 그런 다음 필요한 요소를 탐색 할 수 있습니다.

$(this).closest('.entry').find('.img-preview .expanded-image'); 

또한 Ron은 클릭 이벤트를 반복 한 다음 바인딩하지 않아야한다고 제안했습니다. 간단하게 할 수 있습니다

$('.entry .content .more-text').click(function(){ 
    $(this).closest('.entry').find('.img-preview .expanded-image'); 
}) 
1

$('.content span.more-text').click(function(event) { 
    var $imgs = $(this).closest('.entry').find('.img-preview .expanded-image'); 
    // work with $imgs here... 
});