如何根据当前网址在javascript中添加语句?

时间:2009-11-08 00:15:09

标签: javascript

基本上我想查看用户所在的url并将其与默认值进行比较,然后运行语句

假设我的网址是https://stackoverflow.com/questions/ask,我正在尝试这样做,而且它无效:

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

感谢您的帮助(我知道的noob问题)

3 个答案:

答案 0 :(得分:1)

尝试一下,你错过了indexOf方法。

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

但我相信你应该离开窗口对象,我认为文档已被弃用(但仍然有效)。

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

您还想检查索引是否大于负数,因为零在技术上是正确的位置。

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

window.location.href为您提供完整的网址。您还可以访问其他位置信息,例如protocolpathnamehashhost

if(window.location.pathname == '/questions/ask')
相关问题