【问题标题】:Check if url contains string with JQuery [duplicate]检查url是否包含带有JQuery的字符串[重复]
【发布时间】:2014-03-10 05:00:46
【问题描述】:

我有一个带有选择选项的页面,我正在使用 JQuery 刷新页面并在单击选项时将字符串添加到 url。现在我需要一种方法来检查浏览器 url 以查看它是否包含所述字符串。

查看其他线程,我认为indexOf 会起作用,但是在尝试这个时它不起作用。我还要如何检查 URL 是否包含 ?added-to-cart=555 之类的内容?完整的 URL 通常看起来像:http://my-site.com,在单击其中一个选项后,页面重新加载后看起来像这样:http://my-site.com/?added-to-cart=555。我只需要检查 URL 是否包含 ?added-to-cart=555 位。

这是我所拥有的:

jQuery("#landing-select option").click(function(){

 $('#product-form').submit();

    window.location.href += $(this).val()

});

jQuery(document).ready(function($) {
if(window.location.indexOf("?added-to-cart=555") >= 0)
            {
                 alert("found it");
            }
});

【问题讨论】:

标签: javascript jquery url


【解决方案1】:

使用 Window.location.href 获取 javascript 中的 url。它是 属性将告诉您浏览器的当前 URL 位置。 将属性设置为不同的值将重定向页面。

if (window.location.href.indexOf("?added-to-cart=555") > -1) {
    alert("found it");
}

【讨论】:

  • 感谢您的回答。
  • 解释一下“> -1”在这种情况下的作用可能会有所帮助......看起来添加这个只是检查这个字符串是否存在于窗口href中。有没有其他方法可以解决这个问题?
  • @john_h 是的,在 javascript indexOf 方法中返回字符串的位置。如果搜索字符串可用,则返回大于或等于零 (>=0)。如果它不可用,它总是返回 -1。
【解决方案2】:

window.location 是一个对象,而不是一个字符串,所以你需要使用 window.location.href 来获取实际的字符串 url

if (window.location.href.indexOf("?added-to-cart=555") >= 0) {
    alert("found it");
}

【讨论】:

    【解决方案3】:
    if(window.location.href.indexOf("?added-to-cart=555") >= 0)
    

    这是window.location.href,而不是window.location

    【讨论】:

      【解决方案4】:

      使用hrefindexof

      <script type="text/javascript">
       $(document).ready(function () {
         if(window.location.href.indexOf("added-to-cart=555") > -1) {
         alert("your url contains the added-to-cart=555");
        }
      });
      </script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-13
        • 1970-01-01
        • 1970-01-01
        • 2012-01-05
        • 2012-03-28
        • 2012-04-21
        • 2021-08-17
        相关资源
        最近更新 更多