检查url是否包含带有JQuery的字符串
我有一个包含选择选项的页面,我使用JQuery刷新页面,并在单击选项时向URL添加字符串。 现在我需要一种方法来检查浏览器URL以查看它是否包含所述字符串。
看看其他线程,我认为indexOf
会起作用,但是在尝试这个时它不起作用。 我怎样检查URL是否包含类似于?added-to-cart=555
? 完整的URL通常如下所示: http://my-site.com
: http://my-site.com
,点击其中一个选项后,页面重新加载后看起来像这样: http://my-site.com/?added-to-cart=555
: 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"); } });
使用Window.location.href来获取javascript中的url。 它是一个告诉您浏览器当前URL位置的属性。 将属性设置为不同的属性将重定向页面。
if (window.location.href.indexOf("?added-to-cart=555") > -1) { alert("found it"); }
window.location是一个对象,而不是一个字符串,所以你需要使用window.location.href来获取实际的字符串url
if (window.location.href.indexOf("?added-to-cart=555") >= 0) { alert("found it"); }
使用带有indexof
href
if(window.location.href.indexOf("?added-to-cart=555") >= 0)
它是window.location.href
,而不是window.location
。