【问题标题】:Add class to specific instance of div using :has使用 :has 将类添加到 div 的特定实例
【发布时间】:2017-03-17 12:49:37
【问题描述】:

我正在尝试将一个类添加到单个 div(或多个,取决于搜索结果返回的内容)但是我下面的代码是将类添加到页面上的所有 .price.full div,而不是而不仅仅是应用于与:has 匹配的那些。

jQuery(document).ready(function() {
    jQuery('.price.full p.price:has(small)').closest('.price.full').addClass('price-enquiry');
});

HTML

    <div class="price-rating">

    <span class="price full price-enquiry">
        <div itemprop="offers" itemscope="" itemtype="http://schema.org/Offer">

            <p class="price"><small>+44 (0) 1395<br> 444099</small></p>

            <meta itemprop="price" content="0">
            <meta itemprop="priceCurrency" content="GBP">
            <link itemprop="availability" href="http://schema.org/InStock">

        </div>

    </span>
    <div class="product-codes">
        <span class="oe-code">
            OE Code: 82-5323/4          
        </span><!-- .oe-code -->
        <span class="sku">
            SKU: MG41           
        </span>
    </div><!-- .product-codes -->
</div>

【问题讨论】:

  • 你的 jQuery 看起来不错。我们需要查看 HTML 以诊断问题
  • 您询问的是 DOM 选择,但没有向我们展示页面的外观。很难提供帮助。
  • small 元素在哪里?当您询问客户端 DOM 选择时,为什么要发布 PHP?
  • 现在你有&lt;small&gt;,但没有&lt;p&gt;
  • 您需要在发布之前验证您的示例是否确实代表了问题,而不是仅仅在帖子中抛出一些代码。即使是现在,也没有任何问题的证明。向我们展示工作正常而不是给我们带来麻烦有什么帮助?

标签: javascript jquery


【解决方案1】:

:has(small),你不是说:has(.small)吗?

您的选择器表示您正在寻找.price.full 中的p.price,其中包含标记名为small 的元素。

我同意其他人关于显示完整 html 以获得正确答案的观点。

【讨论】:

  • small 是一个有效的 dom 元素。所以你可能错了。
  • 如果没有 &lt;small&gt; 元素,则选择器将不匹配任何内容,而不是问题中指出的所有 .price.full 元素。
  • 没有 html 你不能肯定地说
猜你喜欢
  • 1970-01-01
  • 2012-04-06
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
相关资源
最近更新 更多