为什么 127.0.0.1/routeToFile/index.html 不起作用?

问题描述

我正在本地主机地址上构建站

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

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

解决方法

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

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