Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...