问题
I'm trying to pull different stylesheets in my main.js folder depending on the time of day. However, I keep receiving a file not found error in the console.
When I open up inspect element. The day.css file appears in the DOM, but in the console I receive a file not found error and the file path is incorrect.
The browser shows the path as: file:///Users/myname/Documents/directory/foodclock/day.css
but what it should be is: file:///Users/myname/Documents/directory/foodclock/css/day.css
---This is my Javascript code----
function getStylesheet() {
var currentTime = new Date().getHours();
if (0 <= currentTime&¤tTime < 5) {
document.write("<link rel='stylesheet' href='night.css' type='text/css'>");
}
if (5 <= currentTime&¤tTime < 11) {
document.write("<link rel='stylesheet' href='morning.css' type='text/css'>");
}
if (11 <= currentTime&¤tTime < 16) {
document.write("<link rel='stylesheet' href='day.css' type='text/css'>");
}
if (16 <= currentTime&¤tTime < 22) {
document.write("<link rel='stylesheet' href='evening.css' type='text/css'>");
}
if (22 <= currentTime&¤tTime <= 24) {
document.write("<link rel='stylesheet' href='night.css' type='text/css'>");
}
}
getStylesheet();
Any suggestions for troubleshooting this issue? Thanks in advance!
回答1:
Add "css/" in every "href" element. Like this:
function getStylesheet() {
var currentTime = new Date().getHours();
if (0 <= currentTime&¤tTime < 5) {
document.write("<link rel='stylesheet' href='css/night.css' type='text/css'>");
}
if (5 <= currentTime&¤tTime < 11) {
document.write("<link rel='stylesheet' href='css/morning.css' type='text/css'>");
}
if (11 <= currentTime&¤tTime < 16) {
document.write("<link rel='stylesheet' href='css/day.css' type='text/css'>");
}
if (16 <= currentTime&¤tTime < 22) {
document.write("<link rel='stylesheet' href='css/evening.css' type='text/css'>");
}
if (22 <= currentTime&¤tTime <= 24) {
document.write("<link rel='stylesheet' href='css/night.css' type='text/css'>");
}
}
getStylesheet();
回答2:
You need to specify css/ in front of all href links because the css stylesheets are present in different directory css
function getStylesheet() {
var currentTime = new Date().getHours();
if (0 <= currentTime&¤tTime < 5) {
document.write("<link rel='stylesheet' href='css/night.css' type='text/css'>");
}
if (5 <= currentTime&¤tTime < 11) {
document.write("<link rel='stylesheet' href='css/morning.css' type='text/css'>");
}
if (11 <= currentTime&¤tTime < 16) {
document.write("<link rel='stylesheet' href='css/day.css' type='text/css'>");
}
if (16 <= currentTime&¤tTime < 22) {
document.write("<link rel='stylesheet' href='css/evening.css' type='text/css'>");
}
if (22 <= currentTime&¤tTime <= 24) {
document.write("<link rel='stylesheet' href='css/night.css' type='text/css'>");
}
}
getStylesheet();
来源:https://stackoverflow.com/questions/23594863/javascript-file-path-not-linking-correctly