问题
I'm building a website to organize comics collections.
So you have on the left a list of yours comics and if you click on one of them, the page with the details about that comic is loaded on the right with AJAX with the jQuery load()
function.
I don't have a page for every comic but for every serie (one for all the "Walking dead", one for all the "Spiderman"....) so on every page that can be a lot of different comics.
However when clicking on a specific comic I not only want to load the correct page but also to go at the correct position in this page.
I have anchors in every page (#i12,#i13 with a unique number each time).
How can I, after the content is loaded using AJAX, go to the correct anchor ? I tried to dynamically modify the page URL (adding a #i12 at the end) but without success.
I was using document.location.hash
, bad idea ?
A very simple example : when clicking on the link the page is loaded into the div and I would like the page to scroll to the anchor
#i120
Main page :
<div id="list">
<a href="test.php#i120">Go to num 120</a>
</div>
<div id="content">
</div>
Javascript :
$("a").live('click',function (event)
{
$("#Content").load(this.href);
event.stopImmediatePropagation();
event.preventDefault();
});
Page Test.php :
<div id="i1">Text1</div>
...
...
<div id="i120">Text120</div>
回答1:
First, let's get rid of invalid IDs, they can't start with a number until HTML5, I'd prefix your IDs with something like id="nav1"
.
That part is cleanup, what you can do for the scrolling is this:
$("a").live('click', function(event) {
var hash = this.hash;
$("#Content").load(this.href, function() {
document.location.hash = hash;
});
event.stopImmediatePropagation();
event.preventDefault();
});
That'll run once the content is loaded, so there's something to scroll to. That approach instantly goes there, so to animate it...that's easy enough as well:
$("a").live('click', function(event) {
var hash = this.hash;
$("#Content").load(this.href, function() {
var st = $(hash).scrollTop();
$('html, body').animate({ scrollTop: st }, 200); //200ms duration
});
event.stopImmediatePropagation();
event.preventDefault();
});
We're storing this.hash
as a variable because inside that callback, this
will refer to the #Content
element, not the anchor we clicked on.
回答2:
Jquery ScrollTo is probably your best bet.
Otherwise I would suggest having some invisible links on the page (like <a href="#1" id="link1"></a>) and then after the ajax completes and you have the id # you run:
$("#link" + idnumber).click();
Simple, but very effective.
来源:https://stackoverflow.com/questions/4056339/loading-with-ajax-and-going-to-anchor-in-loaded-content