javascript - 使用任一 JavaScript 来定位同级元素

标签 javascript jquery html

我已经被这个问题困扰了一整个下午了。

所以我有一个显示产品列表的网上商店,而不是在此处发布代码,我会在概念上进行,以简化问题。希望有人能指出我正确的方向。

我有一个 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 生成的自定义字段/属性)。

最佳答案

使用 filter 的组合和 next :

$( ".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/

相关文章:

javascript - 我可以创建一个矩阵来根据三个输入变量设置两个变量的状态吗?

javascript - 使用jquery从chrome中的xml节点获取内部xml

javascript - 有没有办法根据盒子中剩余的空间显示按钮

html - 仅降低 bg 颜色的不透明度,不适用于内容或边框

html - 使用客户端代码为不同的设备设置不同的视口(viewport)宽度?

javascript - D3非圆弧

javascript - 在闭包中自动绑定(bind)作用域变量

javascript - Kendo 图表绑定(bind)到 JSON

javascript - 排序动画 JQuery/Velocityjs

HTML CSS 在弹出窗口中显示不同的图像