使用JQuery检查URL是否包含特定字符串

35
我有一个有选择选项的页面,我正在使用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");
            }
});

6
你有没有注意到控制台中的错误TypeError: window.location.indexOf不是一个函数学习如何 调试JavaScript。阅读MDN文档关于 window.location也是有帮助的。 - Felix Kling
更新为 window.location.href.indexOf("要匹配的字符串") - Abram
4个回答

99

使用Window.location.href在JavaScript中获取URL。它是一个属性,将告诉您浏览器当前的URL位置。将该属性设置为不同的内容将重定向页面。

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

在这种情况下,解释一下“> -1”的作用可能会有所帮助……看起来添加这个只是检查窗口href中是否存在该字符串。有没有其他解决方法? - john_h
1
@john_h 是的,在JavaScript中,indexOf方法返回字符串的位置。如果搜索字符串可用,则返回大于或等于零(>=0)。如果不可用,则始终返回-1。 - Sudharsan S

10

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


3

使用 indexofhref

<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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接