2014-02-10 3 views
0

나는 오후 내내이 문제에 매달 렸습니다.자바 스크립트를 사용하여 형제 요소를 타겟팅하십시오

그래서 여기에 코드를 게시하는 대신 제품 목록을 표시하는 webshop이 있습니다. 문제를 간단하게하기 위해 개념적으로 할 것입니다. 누군가가 바른 방향으로 나를 가리킬 수 있기를 바랍니다.

<div class="product-container"> 
    <div class="product-price">Price info</div> 
</div> 

<div class="product-container"> 
    <div class="product-price">Price info</div> 
    <div class="production-options"> 
     <select id="selectoptions1" name="product1" class="attribute_list"> 
      <option value="Colour (please select)">Colour (please select)</option> 
      <option value="White">White</option> 
      <option value="Navy Blue">Navy Blue</option> 
     </select> 
    </div> 
</div> 

<div class="product-container"> 
    <div class="product-price">Price info</div> 
</div> 

당신은 중간 컨테이너가 자식 클래스 production-options을 가지고 있음을 알 수 있습니다 :

나는 다음과 같은 DIV 클래스의 목록을 가지고있다. 제품 컨테이너에 product-options이라는 자식이 있는지 여부를 감지하는 JS 함수를 작성하고자하는 경우 product-price의 채우기를 20px로 설정합니다.

그래서 javascript는 다음과 같습니다. 그것은 단지 형제 product-options와 클래스 product-price에 영향을 미칠 수 있도록

이제
if($(".product-options")) { 
    $(".product-price").css("padding-top", "20px"); 
} 

이 클래스 이름 product-price 모든 요소에 영향을 미칠 것입니다, 내가 그것을 어떻게해야합니까? (ID를 사용하는 것은 옵션이 아닙니다. 이는 virtuemart가 생성 한 사용자 정의 필드/속성이기 때문입니다).

답변

2

filternext과의 조합을 사용하여 :

$(".product-price").filter(function() { 
    return $(this).next(".production-options").length; 
}); 

filter 반환 된 조건과 일치하는 경우에만 product-price 요소를 보장한다. next은 DOM의 다음 형제가 클래스 production-options을 갖도록합니다. 다음 production-options 요소를 대상으로

$.each($('.product-container'), function() { 
    var $this = $(this); 
    if($this.find(".product-options").length) { 
     $this.find('.product-price').css("padding-top", "20px"); 
    } 
}); 
+0

고맙습니다을 선택합니다! 나는 설명을 바르게 평가한다, 나는 잠시 길을 잃었다. .. 그러나 이것은 내가 필요로했던 정확하게 것이다! 좋은 설명. 사실 그들은 모두 다음과 같습니다. –

1

다음 product-price 어디 (단지 바로 옆) 일 수있는 경우 대신 siblings 선택을 사용할 수 있습니다 이전 product-price 요소를 찾을 수

$('.production-options').prev('.product-price').css("padding-top", "20px"); 

데모 : Fiddle

+2

'if ($ (this) .find (".product-options"))'는 항상 true입니다. – jfriend00

1

하나 쉬운 솔루션의 동생 :이 코드를 시도 할 수 있습니다

$(".product-price").filter(function() { 
    return $(this).siblings(".production-options").length; 
}); 
1

.parents을 사용하여 상위 항목을 선택하십시오.

$(".production-options").parents(".product-container"); 

사용 .prev 직접 .product-price

$(".production-options").prev(".product-price"); 
관련 문제