【问题标题】:Why 127.0.0.1/routeToFile/index.html does not working?为什么 127.0.0.1/routeToFile/index.html 不起作用?
【发布时间】:2021-05-23 04:01:50
【问题描述】:

我正在本地主机地址上构建站点,并且

if(window.location=="127.0.0.1/routeToTheFile/index.html"){
//anything
}

不工作。一切正常,直到我需要在 main.js 中进行 if 选择,因为 JavaScript 代码不应该为网站上的每个页面做同样的事情。如果选择的这条路线与我可以访问我的项目的路线相同,因此路线没有错。那么这个 if 选择有什么问题呢?

【问题讨论】:

  • window.location 是一个完整的 URL,所以它类似于 https://127.0.0.1/routeToTheFile/index.html
  • 你不能省略 https:// 部分,因为你正在与 == 完全匹配
  • 供以后参考,调试条件很简单。您只需console.log(window.location) 即可查看输出内容。然后你就可以看到为什么== 条件失败了。

标签: javascript jquery localhost


【解决方案1】:

window.location 包括协议(很可能是本地主机上的 http://)。您应该将协议添加到 127.0.0.1/routeToTheFile/index.html。但最好的方法是使用 window.location.pathname 并编写以下代码:

if (window.location.pathname =="/routeToTheFile/index.html"){
  //anything
}

【讨论】:

    猜你喜欢
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    相关资源
    最近更新 更多