我有一个页面,我按字母顺序显示产品列表。当用户开始滚动
我的页面顶部有字母表列表(AZ),因此当用户点击任何字母表时,我需要将页面滚动到以该字母开头的产品列表
如果已加载div,则该功能正常工作,即如果用户已滚动并且加载了以D开头的产品,则用户单击页面顶部的字母D. 如果没有加载带有字母D的产品列表,那么我加载AD中的所有产品,无论哪个尚未加载,但我无法滚动到div的顶部,其中以D开头的产品列表。
如果有任何人有任何指示来解决问题,请帮忙。 提前致谢
以下是我的javascript代码的代码段
$('.jump').click(function () {
var alphabet = $(this).text();
var jumpToId = "#" + alphabet.toUpperCase();
var targetAlphabetAscii = alphabet.charCodeAt(0);
if (targetAlphabetAscii >= nextAlphabet)
{
var current = "";
do {
current = GetNextAlphabet();
//This function loads the list of products and appends
//to a existing div on the page.
GetProductData(current);
} while (current != alphabet);
}
//The problem is here .. I dont get the offset because till the time the following
//code is executed the div with the selector jumpToId is not loaded..
//so I get undefined error for .offset() method and cannot scroll
var offset = $(jumpToId).offset();
offset.left -= 20;
offset.top -= 20;
$('html, body').animate({
scrollTop: offset.top,
scrollLeft: offset.left
});
});
HTML锚点,即页面顶部的字母列表如下所示
<ul>
<li class="circle"><a class="jump" href="#A">a</a></li>
<li class="circle"><a class="jump" href="#B">b</a></li>
<li class="circle"><a class="jump" href="#C">c</a></li>
<li class="circle"><a class="jump" href="#D">d</a></li>
</ul>
答案 0 :(得分:0)
您需要添加滚动功能作为GetDataContent()
功能的回调。类似的东西:
//Define scrolling function
var doScrolling = function(current){
var offset = $(current).offset();
offset.left -= 20;
offset.top -= 20;
$('html, body').animate({
scrollTop: offset.top,
scrollLeft: offset.left
});
};// end scrolling function
// now define your fetch data function
var GetProductData = function(current, isManualLoad){
$.ajax( "example.php" ).done(function() {
// ... append your content
...
if( ! isManualLoad ){
// and scroll to it
doScrolling( current );
}
});
};
更新:根据OP的评论
为回调添加了标记