2014-02-10 19 views
0

我一直堅持這一整個下午。使用任何一個javascript來定位同級元素

所以我有一個網上商店顯示產品列表,而不是在這裏發佈代碼,我會在概念上做到這一點,以簡化問題。希望有人能指引我正確的方向。

我有類似以下的div類的列表:

<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。我想寫一個JS函數來檢測一個產品容器是否有一個名爲product-options的孩子,如果存在,那麼將product-price的填充設置爲20px或其他。

所以JavaScript看起來像這樣。

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

現在,這將影響到所有使用類名稱product-price的元素,我怎麼做,以便它只能與兄弟姐妹product-options影響類product-price? (使用ID不是一個選項,因爲這些是由virtmart生成的自定義字段/屬性)。

回答

2

使用的filternext的組合:

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

filter將確保僅product-price匹配被返回的條件的元素。 next將確保DOM中的下一個兄弟節點有一個類production-options。如果product-price可以在任何地方(不只是直接旁邊),您可以使用siblings選擇,而不是:

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

感謝名單!我很欣賞這個解釋,我迷了一會兒......但這正是我需要的!很好的解釋。實際上它們都是:) –

1

你可以試試這個代碼:

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

'if($(this).find(「.product-options」))'總是如此。 – jfriend00

1

一個簡單的解決方案SIS的production-options元素目標則找到以前product-price元素

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

演示:Fiddle

1

使用.parents選擇父級。

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

使用.prev直接選擇.product-price

$(".production-options").prev(".product-price"); 
相關問題