douweibiao8471 2015-12-29 02:33
浏览 75
已采纳

ajax调用后滚动到某个元素

I'm trying to scroll to a certain element on the page after an ajax call, but it's not working for some reason. What am I doing wrong?

test.php

<style>
#divOne {
border: 1px solid red;
height: 100%;
width: 100%;
}
#divTwo {
border: 1px solid blue;
height: 100%;
width: 100%;
}
</style>

<input id = 'click' type = 'submit' value = 'Click' onclick = "ajaxCall('testx.php')">
<div id = 'divOne'></div>
<div id = 'divTwo'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
<script type = "text/javascript"> 

function ajaxCall(action) {

    $.ajax({
        type: "POST",
        url: action,
        error: function(xhr,status,error){alert(error);},
        success:function(data) {
            document.getElementById('divTwo').innerHTML = data;        
        }, //end of success:function(data)
        complete:function(data) {
            $("#click").click(function (){
                $('html, body').animate({
                    scrollTop: $("#divTwo").offset().top
                }, 2000);   
        } //end of complete:function(data)
    }); //end of $.ajax({

} //end of function ajaxCall()

</script>

testx.php

<?php

echo "Hello World!";

?>

Expected Result:

Hello World! 
(The page to scroll to #divTwo)

Actual Result:

Hello World! 
(The page DID NOT scroll to #divTwo)
  • 写回答

1条回答 默认 最新

  • dqrzot2791 2015-12-29 03:00
    关注

    Your complete function is just defining a click handler, not actually performing the scroll. Just put the code that does the scroll, without putting it inside .click().

        complete:function(data) {
            $('html, body').animate({
                scrollTop: $("#divTwo").offset().top
            }, 2000);   
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100