0

我遇到了 jQuery scrollTo 插件的问题。我有 2 个 DIV(nav2content),我正在通过 ajax 调用填充它们:

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

如您所见,在获取内容后,我将其附加,然后尝试通过 anchorId 滚动到该目标 div 中的某个位置。这是通过doScrollTo包装 jQuery-Plugin-function 的 -function完成的scrollTogo是 ajax 调用的包装器。在进行 get-Requests 之前,它会从给定的输入参数中提取文件名和 id(由“#”分隔)。以下是这一切的名称:

myJs.go( 'file_a.html#anchor1', 'file_b.html#anchor2' );"

编辑:使用一个 DIV,nav2DIV,一切正常。但是另一个 DIVcontent有时会滚动,有时则不会。而且,如果它被滚动并且将DIV的滚动条向上移动然后go再次调用,它就不再滚动了。正如我所说,这一切都适用于nav2DIV ......

有人知道我在做什么错吗?

谢谢。

4

1 回答 1

0
$.get(targetFile, function(data) {
    $('#'+targetDivId).html( data );
});
if(anchorId !== null){
        this.doScrollTo(targetDivId, anchorId);
}

您在doScrollToXMLHttpRequest 完成之前调用。

这就是您传入的回调函数的全部意义$.get,它不会立即执行,而是仅在异步 HTTP 请求完成时执行。该get方法本身会立即返回,因此当您使用if.

如果您希望在内容加载后立即进行滚动,则需要将该调用放在您传递给的回调函数中get。但请注意,this回调函数中并未保留它,因此您必须bind使用它或使用闭包:

var that= this;
$.get(targetFile, function(data) {
    $('#'+targetDivId).html( data );
    if(anchorId !== null){
        that.doScrollTo(targetDivId, anchorId);
    }
});
于 2010-03-03T10:23:06.177 回答