jQuery 平滑滚动中断 AJAX 调用

jQuery smooth scoll breaks with AJAX call

我已经搜索过,我已经搜索过这个问题的可能原因。但每次我搜索时都会得到 "how to add smooth scrolling"。这不是问题。我有一个 wordpress 设置,平滑滚动在每个实例中都可以正常工作,除了从 JS 文件附加的结果。

$(document).ready(function(){
function descriptions(){
    var apiCall = '[APIRUL]';

    $.ajax({
        url: apiCall,
        type: 'get',
        dataType : 'json',
        success: function(data){
            $.each(data, function(i, p) {
                var name = p.name;
                var namelc = p.namelc; //lowercase
                var description = p.description;
                var output = '<div id="' + namelc + '"><h3">' + name + '</h3><p>' + description + '<br /><a href="#table">back to top</a></p></div>';

                $('#description').append(output);
            });
        },
        error: function(xhr, status, error) {
            console.log(error);
        }
    });
}descriptions();
});

一切正常returns。 jQuery 或 AJAX 本身没有问题。 但是由于某些原因, "a href="#table"" "jumps" 返回table(在描述上方)并添加哈希地址(例如 http://example.com/somepage/#anchor)而不是对其进行缓和(就像同一页面上的所有其他锚 link 一样。即没有错平滑滚动。其他东西干扰)。

我确定有针对此行为的解释和解决方案。但我就是找不到它,因为正如我之前提到的,每次我搜索 "smooth scroll not working" 时,我都会得到大量的 "how to add smooth scroll" 结果。

非常感谢任何帮助,无论是全面的还是正确的方向! /卡住!

如果您使用来自 here 的 JQuery 平滑滚动,看起来它的处理方式就像一个侦听器。如果你用 AJAX 注入,link 上将没有监听器。重新运行绑定 - 像这样:

$('#description a').smoothScroll();

在您的代码中的这一行之后:

$('#description').append(output);

所以,感谢 Peter Mark 的回答(谢谢你!真的。我已经被困在这个问题上一天多了。如果没有你的帮助,它会更长,那是肯定的!)我明白了什么是继续进行,这有助于解决问题。现在,无需挖掘文件层来查看初始平滑滚动的来源(监听器的名称),这是一个可行的解决方案。将漂亮的平滑滚动带回所有 jQuery 附加元素 :D

$('a').click(function(){
    $('html, body').animate({
        scrollTop: $(this.hash).offset().top
    },350,'easeInOutExpo');
    return false;
});

就像 Peter 解释的那样,这需要在 AFTER 追加(否则我们将只针对现有的锚点,而不是我们 creating/injecting 的新锚点追加)。