Javascript文件路径链接不正确

Javascript file path not linking correctly

本文关键字:不正确 链接 路径 文件 Javascript      更新时间:2023-09-26

我试图在我的main.js文件夹拉不同的样式表取决于一天的时间。但是,我一直在控制台收到一个文件未找到错误。

当我打开inspect元素。.css文件出现在DOM中,但在控制台中,我收到一个文件未找到错误,文件路径不正确。

浏览器显示路径如下:文件:///用户/名字/文件/目录/foodclock day.css

,但它应该是:文件:///用户/名字/文件/目录/foodclock/css/day.css

——这是我的Javascript代码----

function getStylesheet() {
var currentTime = new Date().getHours();
if (0 <= currentTime&&currentTime < 5) {
document.write("<link rel='stylesheet' href='night.css' type='text/css'>");
}
if (5 <= currentTime&&currentTime < 11) {
document.write("<link rel='stylesheet' href='morning.css' type='text/css'>");
}
if (11 <= currentTime&&currentTime < 16) {
document.write("<link rel='stylesheet' href='day.css' type='text/css'>");
}
if (16 <= currentTime&&currentTime < 22) {
document.write("<link rel='stylesheet' href='evening.css' type='text/css'>");
}
if (22 <= currentTime&&currentTime <= 24) {
document.write("<link rel='stylesheet' href='night.css' type='text/css'>");
}
}
getStylesheet();

对解决这个问题有什么建议吗?提前感谢!

在每个"href"元素中添加"css/"。这样的:

function getStylesheet() {
var currentTime = new Date().getHours();
if (0 <= currentTime&&currentTime < 5) {
document.write("<link rel='stylesheet' href='css/night.css' type='text/css'>");
}
if (5 <= currentTime&&currentTime < 11) {
document.write("<link rel='stylesheet' href='css/morning.css' type='text/css'>");
}
if (11 <= currentTime&&currentTime < 16) {
document.write("<link rel='stylesheet' href='css/day.css' type='text/css'>");
}
if (16 <= currentTime&&currentTime < 22) {
document.write("<link rel='stylesheet' href='css/evening.css' type='text/css'>");
}
if (22 <= currentTime&&currentTime <= 24) {
document.write("<link rel='stylesheet' href='css/night.css' type='text/css'>");
}
}
getStylesheet();

你需要在所有的href链接前指定css/,因为css样式表存在于不同的目录css

function getStylesheet() {
var currentTime = new Date().getHours();
if (0 <= currentTime&&currentTime < 5) {
document.write("<link rel='stylesheet' href='css/night.css' type='text/css'>");
}
if (5 <= currentTime&&currentTime < 11) {
document.write("<link rel='stylesheet' href='css/morning.css' type='text/css'>");
}
if (11 <= currentTime&&currentTime < 16) {
document.write("<link rel='stylesheet' href='css/day.css' type='text/css'>");
}
if (16 <= currentTime&&currentTime < 22) {
document.write("<link rel='stylesheet' href='css/evening.css' type='text/css'>");
}
if (22 <= currentTime&&currentTime <= 24) {
document.write("<link rel='stylesheet' href='css/night.css' type='text/css'>");
}
}
getStylesheet();