2014-02-10 23 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"); 
相关问题