ajax调用后滚动到某个元素

时间:2015-12-29 02:33:28

标签: javascript php jquery ajax

我正在尝试在ajax调用后滚动到页面上的某个元素,但由于某种原因它不起作用。我究竟做错了什么?

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!";

?>

预期结果:

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

实际结果:

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

1 个答案:

答案 0 :(得分:5)

您的完整功能只是定义一个点击处理程序,而不是实际执行滚动。只需将执行滚动的代码放在.click()内。

    complete:function(data) {
        $('html, body').animate({
            scrollTop: $("#divTwo").offset().top
        }, 2000);   
    }