How do I load an web page into a div upon a user click on a link?
I'm using jquery and I'm looking to have a user click on a link and load the server response (in this case a one line confirmation) in the same div the link is in. I've gone round and round on this and can't seem to get it right. Here is the code I have from another post on this site which was similar but not close enough for me to grok...
<a href="http://10.0.1.2:8888/?ACT=24&tag_id=8" class="load_link">Add to Watchlist*</a>
<script type="text/javascript">
(function($) {
$(function() {
$('.load_link').click(function() {
$(this).next('div').load(this.href);
return false;
});
});
})(jQuery);
</script>
Any ideas what I'm doing wrong?开发者_运维百科
Thanks
If the anchor is wrapped inside a div and you want to load the response in this div you could use the .closest()
method:
<div>
<a href="http://10.0.1.2:8888/?ACT=24&tag_id=8" class="load_link">Add to Watchlist*</a>
</div>
and then:
$(this).closest('div').load(this.href);
if there is a div adjacent to the anchor:
<a href="http://10.0.1.2:8888/?ACT=24&tag_id=8" class="load_link">Add to Watchlist*
<div></div>
then the .next()
method should work.
If you load the content into the containing div then the link gets replaced.
Hence add a span/div with in the main div that has the link and use this child span/div to load the content.
e.g:
<div>
<span class="content"></span>
<a href="http://10.0.1.2:8888/?ACT=24&tag_id=8" class="load_link">Add to Watchlist*</a>
</div>
<script type="text/javascript">
(function($) {
$(function() {
$('.load_link').click(function() {
$(this).siblings(".content").load(this.href);
return false;
});
});
})(jQuery);
</script>
Starting point is to install Firebug and enter a debug session so that you can step through the code. Also you want to do the binding on document.ready() to ensure you bind after DOM is ready.
精彩评论