I've got problems with the jQuery scrollTo plu开发者_运维百科gin.
I've got 2 DIVs (nav2
and content
) and I'm filling them via ajax calls:
var myJs = { ...
getWithAjax : function( targetFile, targetDivId, anchorId ) {
// get is jquery function and wraps ajax call
$.get(targetFile, function(data) {
$('#'+targetDivId).html( data );
if(anchorId !== null){
myJs.doScrollTo(targetDivId, anchorId);
}
});
},
go : function(file1, file2) {
var file1Array, file2Array = new Array();
if(file1 !== null){
file1Array = this.splitLinkFromAnchor(file1);
// update nav2 div
this.getWithAjax(file1Array[0], "nav2", file1Array[1]);
}, //... same with file2 but other div "content"
doScrollTo : function( divId, anchorId ) {
$( '#' + divId ).scrollTo( '#' + anchorId, 0 );
}
// ... further functions
} // end of object literal
As you see, after getting the content I append it and then try to scroll to a certain position in that target div via an anchorId. This is done via the doScrollTo
-function that wraps the jQuery-Plugin-function scrollTo
. go
is a wrapper for the ajax calls. Before making get-Requests it extracts filename and id (split by '#') from given input parameters.
Here's how this all is called:
myJs.go( 'file_a.html#anchor1', 'file_b.html#anchor2' );"
EDIT: With one DIV, the nav2
DIV, everything works fine. But the other DIV content
is sometimes scrolled, sometimes not. And also, if it is scrolled and a i move the scrollbar of the DIV up and then call go
again, it does not scroll anymore. And as I said, this all works fine with the nav2
DIV...
Anybody got an idea what I'm doing wrong?
Thanks.
$.get(targetFile, function(data) {
$('#'+targetDivId).html( data );
});
if(anchorId !== null){
this.doScrollTo(targetDivId, anchorId);
}
You're calling doScrollTo
before the XMLHttpRequest has completed.
That's the whole point of the callback function you pass into $.get
, it doesn't execute straight away, but only when the asynchronous HTTP request is finished. The get
method itself returns immediately, so the callback hasn't run and filled in the content by the time you get to the next line with the if
.
If you want the scroll to happen just after the content is loaded, you need to put that call inside the callback function you're passing to get
. But note that this
isn't preserved in callback functions, so you'd have to bind
it or use a closure:
var that= this;
$.get(targetFile, function(data) {
$('#'+targetDivId).html( data );
if(anchorId !== null){
that.doScrollTo(targetDivId, anchorId);
}
});
精彩评论