Reputation: 2185
i'm loading external contents inside a page with .load()
.
in my index.html
i have this code:
$(document).ready(function(){
$("#conteudo_mostrar").load("inicial.html");
});
and
<div id="conteudo_mostrar"></div>
so, in my inicial.html
i have another link to contact.html
, and when someone clicks that link (contact link inside of inicial.html
) I need to replace the inicial.html
to contain contact.html
inside the same div #conteudo_mostrar
on the page index.html
How to do that??
Upvotes: 2
Views: 3131
Reputation: 15780
You can use .get()
and suppose you have a link for contact.html
:
<a href="contact.html" id="lnkContact">Contact</a>
Then:
$(document).ready(function() {
$.get('inicial.html', function(data) {
$('#conteudo_mostrar').html(data);
});
$('#lnkContact').live('click', function(e) {
e.preventDefault();
$.get((this).attr('href'), function(data) {
$('#conteudo_mostrar').html(data);
});
});
});
If in case you're going to add more links, you'll just do the same for every id
. If you have another link, let's say for gallery.html
:
<a href="gallery.html" id="lnkGallery">Gallery</a>
You'll just need to append it in your code, just like the one in lnkContact
, just change it to lnkGallery
:
$('#lnkGallery').live('click', function(e) {
e.preventDefault();
$.get((this).attr('href'), function(data) {
$('#conteudo_mostrar').html(data);
});
});
Your whole code will now be:
$(document).ready(function() {
$.get('inicial.html', function(data) {
$('#conteudo_mostrar').html(data);
});
$('#lnkContact').live('click', function(e) {
e.preventDefault();
$.get((this).attr('href'), function(data) {
$('#conteudo_mostrar').html(data);
});
});
$('#lnkGallery').live('click', function(e) {
e.preventDefault();
$.get((this).attr('href'), function(data) {
$('#conteudo_mostrar').html(data);
});
});
});
And for every other links, you just need to make the same changes. Provided that you have an id
attribute to distinguish each link.
A more efficient way by Preston
Tag each link by link
class:
<a href="contact.html" class="link">Contact</a>
<a href="gallery.html" class="link">Gallery</a>
Then:
$(document).ready(function() {
$.get('inicial.html', function(data) {
$('#conteudo_mostrar').html(data);
});
$('.link').live('click', function(e) {
e.preventDefault();
$.get((this).attr('href'), function(data) {
$('#conteudo_mostrar').html(data);
});
});
});
Upvotes: 3
Reputation: 26160
REVISION based on question clarifiations:
It's simple enough. You just need to use live to the link class/id. This binds the link to elements that may not yet exist on the page. Then, within the bind click event, just load the content.html like so:
$(document).ready(function(){
// Load the initial content
$("#conteudo_mostrar").load("inicial.html");
$("#contact_link").live("click", function() {
$("#conteudo_mostrar").load("contact.html");
}
});
Upvotes: 2