JQuery load help
I am trying to use load() to place some html into a div on a page. I have a bunch of links like this:
<div id="slideshow">
<div id="slides">
<div class="projects">
<a href="work/mobus.html" title="Mobus Fabrics Website">
<img src="images/work/mobus.jpg" alt="Mobus Fabrics Website" width="280" height="100" />
</a>
<a href="work/eglin.html" title开发者_JS百科="Eglin Ltd Website">
<img src="images/work/eglin.jpg" alt="Eglin Ltd Website" width="280" height="100" />
</a>
<a href="work/first-brands.html" title="First Brands Website">
<img src="images/work/first-brands.jpg" alt="First Brands Website" width="280" height="100" />
</a>
</div>
<a id="prev"></a>
<a id="next"></a>
</div>
and my jquery code looks like this:
$('.projects a').click(function() {
$('#work').load(this.href);
});
The problem is when clicked the html is placed in the #work div the html is loaded in another page. Please can anyone help?
You need to prevent the default action to stop the href being loaded:
$('.projects a').click(function(event) {
$('#work').load(this.href);
event.preventDefault();
});
You may also see people achieving the same by doing:
$('.projects a').click(function(event) {
$('#work').load(this.href);
return false;
});
However, this method will stop the event bubbling any further, as well as preventing the default action. If you've got any delegate
or live
methods listening for the same event further up the DOM tree, doing return false
will stop these handlers being called.
Edit: For the callback function:
$('.projects a').click(function(event) {
$('#work').load(this.href, function (text) {
alert("This loaded: " + text);
});
event.preventDefault();
});
You have to prevent the event from chaining.. the browser will eventually follow the link.
See preventDefault
精彩评论