繁体   English   中英

如何基于当前URL在JavaScript中添加语句?

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

基本上,我想检查用户使用的是哪个url并将其与默认值进行比较,然后运行一条语句

假设我的网址是https://stackoverflow.com/questions/ask ,我正在尝试执行此操作,但它不起作用:

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

谢谢你的帮助(我知道的菜鸟问题)

试试看,您缺少indexOf方法。

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

但是我相信您应该离开该窗口对象,我认为文档已过时(但仍然可以使用)。

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

您还希望检查索引是否大于负1,因为从技术上讲零是正确的位置。

尝试这个:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM