开发者

How do I add a statement in javascript based on the current url?

Basically I want to check what url the user is on and compare it to a default value and then run a statement

Let's say my url is https://stackoverflow.开发者_开发技巧com/questions/ask, I'm trying to do this, and it's not working:

<script type="text/javascript">
      if(document.location.href('/questions/ask') > 0)
  {
    [do this];
  }

Thanks for the help(noob question I know)


Give this a try, you are missing the indexOf method.

if(document.location.href.indexOf('/questions/ask') > -1)

But I believe you should be going off of the window object, I think document is deprecated (but still works).

if(window.location.href.indexOf('/questions/ask') > -1)

You also want to check to see if the index is greater than negative one because zero is technically a correct position.


Try this:

var loc = new String(window.location);
if(loc.match('/questions/ask')) {
    // do something here
}


window.location.href gives you the whole url. You can also access other properties of location, like protocol, pathname, hash, host.

if(window.location.pathname == '/questions/ask')
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜