Check if url contains string with JQuery [duplicat

2019-01-22 03:07发布

This question already has an answer here:

I have a page with select options and I am using JQuery to refresh the page and add a string to the url when an option is clicked. Now I need a way to check the browsers url to see if it contains said string.

Looking on other threads I thought indexOf would work, but when trying this it doesn't work. How else would I check if the URL contains something like ?added-to-cart=555? The complete URL would normally look like: http://my-site.com, and after clicking one of the options it looks like this after page reload: http://my-site.com/?added-to-cart=555. I just need to check to see if the URL contains that ?added-to-cart=555 bit.

Here is what I have:

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");
            }
});

4条回答
我想做一个坏孩纸
2楼-- · 2019-01-22 03:19
if(window.location.href.indexOf("?added-to-cart=555") >= 0)

It's window.location.href, not window.location.

查看更多
你好瞎i
3楼-- · 2019-01-22 03:37

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");
}
查看更多
在下西门庆
4楼-- · 2019-01-22 03:40

window.location is an object, not a string so you need to use window.location.href to get the actual string url

if (window.location.href.indexOf("?added-to-cart=555") >= 0) {
    alert("found it");
}
查看更多
祖国的老花朵
5楼-- · 2019-01-22 03:41

use href with indexof

<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>
查看更多
登录 后发表回答