Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

JQuery not loading html file

I'm learning HTML/JavaScript by building a sample website on my local computer. I am trying to reuse code and doing so by using JQuery; however it doesn't seem to actually do anything when I use the load function.

I am sampling this via Google Chrome browser.

I've seen examples using other methods such as php, straight javascript using document.write(), but I would like to know how to use it with JQuery

I have already tried:

  • --allow-file-access-from-file with google; as some posts show a known problem

Both html files are in the same location as well.

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<style>
  html{

    background:radial-gradient(#505154,#28292b) no-repeat center center fixed;
    background-size:cover; 
  }
  </style>
  <title>WebPage</title>
  <link rel="icon" href="logo.ico"/>
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
  <div id="navigation"></div>
    <script> 
      $(function(){
        $("#navigation").load("nav.html"); 
      });
    </script> 
</body>
</html>

nav.html:

<p>This is my include file</p>

Is there something I am doing wrong; or missing?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Move your JavaScript to the bottom of the file, right before </body> so that when it runs, your navigation is defined.

Edit (for more clarity):

As the browser loads a file, it reads from top to bottom and runs the JavaScript in real time, since you try to access an element that isn't defined until later on in the page, as by the jQuery standard your .load() will not do anything because the selector was not found.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...