简体   繁体   English

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

[英]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 基本上,我想检查用户使用的是哪个url并将其与默认值进行比较,然后运行一条语句

Let's say my url is https://stackoverflow.com/questions/ask , I'm trying to do this, and it's not working: 假设我的网址是https://stackoverflow.com/questions/ask ,我正在尝试执行此操作,但它不起作用:

<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. 试试看,您缺少indexOf方法。

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. 您还希望检查索引是否大于负1,因为从技术上讲零是正确的位置。

Try this: 尝试这个:

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

window.location.href gives you the whole url. window.location.href为您提供整个网址。 You can also access other properties of location, like protocol , pathname , hash , host . 您还可以访问位置的其他属性,例如protocolpathnamehashhost

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

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

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