简体   繁体   中英

Replace div content using jQuery

I have this code in header.html :

<nav role="navigation">
    <ul class="nav">
        <li><a id="home" href="index.html" class="current">home</a></li>
        <li><a id="about" href="includes/test.html">about</a></li>
        <li><a id="resources" href="#">resources</a></li>
        <li><a id="archive" href="#">archives</a></li>
    </ul>
 </nav>

Now, everything seems fine until my index.html loads files from another folder to fill the divs with id="header" , id="content" and id="footer" using:

$(function() {
    $("#mainhead").load("templates/header.html");
    $("#content").load("templates/content.html");
    $("#footer").load("templates/footer.html");
});

My question is - How can I replace content in the div id="content" with the one from another HTML page that can be accessed by clicking a link in the nav menu?

Change the code that loads the navigation to this...

$("#mainhead").load("templates/header.html", function() {
    $(this).find(".nav a").on("click", function(e) {
        e.preventDefault();             // stop the link from firing as normal
        $("#content").load(this.href);  // load the file specified by the link
    });
});

This will "ajaxify" the links in the header navigation, after it has loaded, so that the content div is loaded for each of the links, without having to navigate away from the page. Just make sure each header link has the correct href value for the content you want it to load.

$("#content").replace("old page","new page");

try this one.

or

$("#content").load(){ location.replace("your page"); }

or

var url = "Your url"; $(location).attr('href',url);

Is this what you meant? This will load the content from header/content/footer pages and load in the appropriate div on click of home.

$("#home").click(function () {
    $("#mainhead").load("templates/header.html", function (data) { $(this).html(data); });
    $("#content").load("templates/content.html", function (data) { $(this).html(data); });
    $("#footer").load("templates/footer.html", function (data) { $(this).html(data); });
});
$("#div").html("Your content");

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