开发者

Why is this simple javascript not working?

New to js here. Basically I am trying to detect the existence of a string in the present page's url with this:

var url 开发者_C百科= window.location;
var param = /\?provider=/i;
if (url.search(param) != -1) {
    alert('it does exist');
} else
    alert('it does not exist');

It works when I manually define the url variable like so

var url = 'http://google.com?provider='

but when I try to grab it dynamically like in the above script it doesn't work, is there any way to make it work?


You want the href property on the location object, like this:

var url = window.location.href;
var param = /\?provider=/i;
if (url.search(param) != -1) {
    alert('it does exist');
} else
    alert('it does not exist');

location isn't a string, it's an object, and doesn't have the .search() method, .href is the string that does.


window.location is an object. Have a look at the entire set of properties of the location object: https://developer.mozilla.org/en/DOM/window.location

What you're after is window.location.href;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜