简体   繁体   中英

How to write a JS function that is used by .html files in different folders?

I'm trying to call a function on my XAMPP server that dynamically changes the current stylesheet of an HTML document. This is what I'm currently doing:

document.getElementById("color-scheme").href = "../colors.css";

The colors.css is obviously one folder above the page that is using this code, hence the "../". Now my problem is that there are dozens of pages in different folder levels that all need to access this colors.css to set the color-scheme. For example:

  • index.php (same folder)
  • news/index.php (one folder in)
  • news/january/index.php (two folders in)... and so on.

This means that every page that isn't exactly one folder above colors.css doesn't work as it can't find the file at "../colors.css", as the server seems to go back beyond the root to find the file.

I feel like manually adding "../" according to the folder's level would be very bad coding, so I don't want to do this:

function LoadColorScheme(var level) {
   var path = "";
   for (var i = 0; i < level; i++) 
      path += "../";
   path += "colors.css";
 }

Is there a better way to do this?

using separate files for css/javascript is not really scalable when your apps grow, you can use some bundler tools like webpack, rollup... to bundle all assets into a single entry file. The tools manage dependencies of the entry files autonomously, hence you would not need the manual import of each asset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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