How to dynamically load content into DIV using Javascript

前端 未结 2 1665
时光说笑
时光说笑 2021-01-16 00:57

I have a website which consists of 5 different pages.

To maintain the design of all the pages, I copied and pasted the code from the main page to all the other HTML

相关标签:
2条回答
  • 2021-01-16 01:37

    What you wanna do, is load content using AJAX (XmlHttpRequest). That means, you have just one page with layout, and content/other pages are loaded without the need of reloading the page.

    For that, you can use jQuerys .load() function. Tl;dr; what you gonna do, is to have content of the website as simple html files, without layout (header etc), and using ajax you are gonna load it into the page.

    Content of your main page index.html could look like this (I removed those images in nav bar)

    <div class="mainwrapper">
      <div class="navbox" id="js-navigation">
        <a href="./about.html">About</a>
        <a href="./location.html">Location</a>
        <a href="./contact.html">Contact</a>
        <a href="./inquiries.html">Inquiries</a>
        <a href="./employees.html">Employees</a>
      </div>
    
      <div id="header"></div>
    
      <div id="js-content">
        <!-- content will be loaded here -->
      </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(document).ready(function() {
        $('#js-content').load('/about.html');
    
        $('#js-navigation a').click(function(e) {
          e.preventDefault();
          $("#js-content").load(e.target.href);
        })
      });
    </script>

    So in the same folder, you will have those other content files, but without navigation, wrappings header etc. Just plain content like:

    <h1>About page</h1>
    <p>Lorem Ipsum</p>
    
    0 讨论(0)
  • 2021-01-16 01:47

    Alright so my approach is a bit different as I use PHP but hopefully I am still able to help you with this. I am working on something similar where I have "index" page that includes a nav bar at the top and empty space below it. After I click on something the content of another php file loads into white space, and said another php file is wrapped into a div I can edit with css. To do this I've used this php command:

    <div>
    <?php
    $page = "MainPanel.php"; // my index
        if (isset($_GET["page"])) {
            $page = $_GET["page"];
        }
        if ($page == "" or $page == "MainPanel.php") {
            $page = "/Main/central.php"; //default page upon running the code.
        }
        $GLOBALS["page"] = $page;
    
    ob_start();
    include($page);
    ob_end_flush();
    ?>
    </div>
    

    This should be it. I don't know php very well and one of my collegues suggested to use this but it's relatively small amount of code and it works well.

    0 讨论(0)
提交回复
热议问题