2014-02-12 54 views
20

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

寻找其他线程我认为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

难道你没有注意到的错误'类型错误: window.location.indexOf不是控制台中的函数吗? [了解如何](http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820)[** debug ** JavaScript](https://developers.google.com/chrome-developer-tools /文档/ JavaScript的调试)。阅读[关于'window.location'的MDN文档](https://developer.mozilla.org/en-US/docs/Web/API/Window.location)也很有帮助。 –

+0

更新到'window.location.href.indexOf(“string-to-match”)' – Abram

回答

62

Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.

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

感谢您的回答。 –

+0

它可能有助于解释在这种情况下“> -1”做什么......它看起来像添加这只是检查此字符串是否存在于窗口href中。有没有不同的方法来解决这个问题? –

+1

@john_h是的,在javascript indexOf方法中返回字符串的位置。如果搜索字符串可用,则返回大于或等于零(> = 0)。如果它不可用,它总是返回-1。 –

3

使用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> 
3
if(window.location.href.indexOf("?added-to-cart=555") >= 0) 

window.location.href,不window.location

9

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

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