【问题标题】:jQuery: Add Class on page load for specific URL pathjQuery:在页面加载时为特定 URL 路径添加类
【发布时间】:2022-11-18 13:45:38
【问题描述】:

我在 Shopify 中有一个特定的产品页面(尽管这肯定适用于在 URL 查询中默认选择变体的任何 URL。我希望在加载此页面时,在加载时立即将一个类添加到其中一个 div .

基本上,它正在寻找在 URL 中包含此变体的 URL。所以我想我可以将它缩短为 ?variant=12345。也许不吧?

我正在尝试这个 jQuery 脚本,但它无法正常工作。这里的正确解决方案可能是什么?

$(document).ready(function() {

var url = window.location.pathname;
if (url.indexOf('/products/my-product?variant=12345') !== -1) {
  $(".sales-widget").addClass('sales-on');
}

【问题讨论】:

    标签: jquery


    【解决方案1】:

    要在 URI 中获取参数,您需要同时使用 location.pathnamelocation.search,如下所示:

    var url = (window.location.pathname + window.location.search).substr(1);
    

    看这个例子:

    $(document).ready(function() {
    
      var url = (window.location.pathname + window.location.search).substr(1);
      if (url.indexOf('/products/my-product?variant=12345') !== -1) {
        $(".sales-widget").addClass('sales-on');
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    【讨论】:

      猜你喜欢
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      • 2015-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-02
      相关资源
      最近更新 更多