如何通过Bootstrap导航栏加载外部HTML内容到HTML5页面主区域
Hey there! You're already off to a great start using jQuery's load() method—this is exactly the right approach for your use case (since HTML imports are off the table for Firefox support). Let's refine your code to make it more robust, maintainable, and aligned with Bootstrap's behavior.
Key Improvements We'll Make
- Target only relevant navigation links (avoid binding events to all
<a>tags) - Update Bootstrap's active navigation state for better UI feedback
- Add error handling for failed content loads
- Reuse logic to follow DRY principles
Modified Working Code
Here's the updated version of your script and minor HTML tweaks:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>My Testpage</title> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <!-- Fixed: <header> was outside <body> in your original code! --> <header> <!-- A header picture here --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <a class="nav-item nav-link active" href="#" data-src="html/home.html">Home <span class="sr-only">(current)</span></a> <a class="nav-item nav-link" href="#" data-src="html/blog.html">Blog</a> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#" data-src="html/act1.html">Action1</a> <a class="dropdown-item" href="#" data-src="html/act2.html">Action2</a> <a class="dropdown-item" href="#" data-src="html/act3.html">Action3</a> </div> </li> </ul> </div> </nav> </header> <main> <div class="container-fluid"> <h1>My Testpage</h1> <section id="content"> <!-- Content from other pages below html/ like loadpage.html should go in here --> </section> </div> </main> <footer class="footer" id="footer"> <!-- Some footer stuff here --> </footer> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script> // Reusable function to load content and update navigation state function loadContent(targetElement, srcUrl, activeLink) { // Update active state: remove from all links, add to current $('.navbar-nav .nav-link, .dropdown-menu .dropdown-item').removeClass('active'); $(activeLink).addClass('active'); // Load content with error handling $(targetElement).load(srcUrl, function(response, status, xhr) { if (status === "error") { $(targetElement).html(`<div class="alert alert-danger">Oops! Failed to load content: ${xhr.status} ${xhr.statusText}</div>`); } }); } // Initial load of home content loadContent('#content', 'html/home.html', '.navbar-nav a[data-src="html/home.html"]'); // Bind click events to all navigation links with data-src attribute $('.navbar-nav a[data-src], .dropdown-menu .dropdown-item[data-src]').on('click', function(e) { e.preventDefault(); // Prevent default link behavior const src = $(this).attr('data-src'); loadContent('#content', src, this); }); </script> </body> </html>
What's Changed & Why?
- Fixed HTML Structure: Moved
<header>inside<body>(it was outside in your original code, which is invalid HTML). - Reusable
loadContentFunction: Encapsulates content loading and active state updates into one function—follows DRY perfectly, no need to repeat code for each link. - Precise Event Binding: Targets only navigation links with
data-srcattributes (not all<a>tags), so other links (like the navbar brand) won't be affected. - Active State Management: Updates Bootstrap's
activeclass when a link is clicked, so users can see which page is currently selected. - Error Handling: Shows a friendly error message if the external HTML file can't be loaded (e.g., file not found, network issues).
- Prevent Default Behavior: Uses
e.preventDefault()to stop the browser from trying to navigate to the#anchor, which avoids unnecessary page jumps.
Important Note for Local Testing
If you're testing this directly from your filesystem (using file:// protocol), some browsers (like Chrome) may block the load() request due to CORS restrictions. To avoid this, use a simple local server:
- For VS Code, install the Live Server extension and open your project with it.
- Or run a Python server:
python -m http.server(Python 3) orpython -m SimpleHTTPServer(Python 2) from your project folder.
This solution is reliable, uses only Bootstrap 4 and jQuery (no server-side tech), and adheres to DRY principles.
内容的提问来源于stack exchange,提问作者Thorsten

