我已经被这个问题困扰了一整个下午了。
所以我有一个显示产品列表的网上商店,而不是在此处发布代码,我会在概念上进行,以简化问题。希望有人能指出我正确的方向。
我有一个 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>
您会注意到中间容器有一个子类生产选项
。我想编写一个JS函数来检测产品容器是否有一个名为product-options
的子容器,如果有,则将product-price
的填充设置为20px 或其他。
所以 javascript 看起来像这样。
if($( ".product-options")) {
$( ".product-price" ).css( "padding-top", "20px" );
}
现在这将影响类名为 product-price
的所有元素,我该如何制作才能使其仅影响具有同级的类 product-price
产品选项
? (不能选择使用 ID,因为这些是由 Virutmart 生成的自定义字段/属性)。
最佳答案
$( ".product-price" ).filter(function() {
return $(this).next(".production-options").length;
});
filter
将确保仅返回符合条件的 product-price
元素。 next
将确保 DOM 中的下一个同级具有类 生产选项
。如果 product-price
可以在任何地方(不仅仅是紧邻),您可以使用 siblings选择器:
$( ".product-price" ).filter(function() {
return $(this).siblings(".production-options").length;
});
关于javascript - 使用任一 JavaScript 来定位同级元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21672000/