开发者

How to load/replace an entire DIV from an external HTML file?

I have the following index.html page set-up:

<html>
  <head>
  </head>
  <body>
    <开发者_C百科;div id="container">
      <div id="header">
      </div>
      <div id="sidebar_menu">
      </div>
      <div id="thecontent">
        <div id="page_banner">
        </div>
        <div id="page_content">
        </div>
        <div id="page_footer">
        </div>
      </div>
    </div>
  </body>
</html>

In addition to this, I have several individual .html files that reflect an option in my sidebar menu, so when the user first lands on the page, they will see index.html file based on the above setup, ie. shows header/menu/the content and footer.

My question is, when the user clicks on say the "About Us" menu option, I actually want to just replace "thecontent" div with the contents of my about-us.html file but without reloading the header and sidebar menu. I just want the entire div "thecontent" to be replaced with the div "thecontent" from my about-us.html file.

Is this possible as like I said, I have several individual .html files and really don't want to duplicate code like my sidebar menu in every page as only my content will be changing based on menu selection.

I looked at jQuery.load() from this tutorial.

I think though this will not work. Also saw the .replacewith() but unsure if this is correct and if it is, unsure how to use in my scenario to go off and replace div with an external .html file.


jQuery's load method has a special syntax that allows you to select what content you want to load from the URL you provide. You simply specify a CSS selector after your URL. (Read the documentation, under "Loading Page Fragments")

For example:

$("#thecontent").load("about-us.html #thecontent");

Hosted demo:

http://jsbin.com/uvera3 (Editable via http://jsbin.com/uvera3/edit)


Description: Load data from the server and place the returned HTML into the matched element.

Thats straight out of the jQuery documentation for .load() which will do exactly what you want.

$('#thecontent').load('/whereever/about-us.html');

All done, Thanks!

.load()


Did you try load? It's exactly what you want:

$('#thecontent`').load('about-us.html');

bound to a link:

$(function() {
    $("#aboutuslink").click(function(){
          $('#thecontent`').load('about-us.html');
         return false;
    }) ;
});
<a href="#" id="aboutuslink">About Us</a>

At http://api.jquery.com/load/ scroll down to the part about loading page fragments.


If the server includes the HTML for the layer that is going to be replaced, you could do something like this:

$.get('/server-side.html', function(data)
{
    $('#content').html($(data).html());
});

Assuming that /server-side.html returns something like this:

<div id="content">
    YOUR CONTENT HERE
</div>

Hope that it helps. Regards.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜