【问题标题】:Javascript auto scroll page up and down and refresh the data periodicallyJavascript自动上下滚动页面并定期刷新数据
【发布时间】:2018-12-29 09:40:41
【问题描述】:

我正在开发一个需要缓慢上下滚动的警报板——每隔几分钟就会使用 Ajax 获取更多数据(为此我已经有了一个名为 getData() 的函数)

到目前为止,我得到了:

$(document).ready(function () {
            getData();

            $("html, body").animate({ scrollTop: $(document).height() }, 20000);
            setTimeout(function () {
                $('html, body').animate({ scrollTop: 0 }, 20000);
            }, 10);
            var scrolltopbottom = setInterval(function () {

                $("html, body").animate({ scrollTop: $(document).height() }, 20000);
                setTimeout(function () {
                    $('html, body').animate({ scrollTop: 0 }, 20000);
                }, 100);

            }, 2000);
            getData();

        });

但是这只会滚动页面并且不会调用 getData()

理想情况下,我想自动上下滚动页面,这样人们就可以阅读页面,无论上面有多少数据,并且每 2 分钟调用一次 getData() 来刷新数据。

该页面包含一个简单的表格,该表格可能有 x 行 - 该数量会随着 getData() 的调用而改变。

getData() 代码

function getData() {
                $.ajax({
                    url: #url#,
                    type: "GET",
                    success: function (data) {

                        $("#alarms tr").remove(); 


                        $.each(data, function (i, item) {
                                    $("#alarms").prepend("<tr class=\"bg-danger\"><td>" + item.name + "</td></tr>");
                                }
                        });
                        $("#refreshed").text(new Date().toLocaleString());
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        $('body').html('<span style="color: red;"><h2>Error retrieving data<!/h1><br/><h3>' + thrownError + '</h3></span>');
                    }
                });

html 页面只有一个带有 thead 和 tbody 的表格

【问题讨论】:

  • 也添加听你的 getData() 函数代码。
  • @dev_ramiz_1707 - 也添加了。
  • 请在浏览器中检查你的网址,看看有没有数据
  • 是的,大约创建了 25 行。这适用于第一次调用 GetData() 但不适用于后续调用。我的问题是如何让页面自行上下滚动,同时每 2 分钟刷新一次数据。
  • 好的,我理解你所有的问题。但您没有创建自动加载新数据代码。

标签: javascript jquery scroll


【解决方案1】:

试试这个代码可能对你有帮助。

$(document).ready(function () {
            getData();

            $("html, body").animate({ scrollTop: $(document).height() }, 20000);
            setTimeout(function () {
                $('html, body').animate({ scrollTop: 0 }, 20000);
            }, 10);
            var scrolltopbottom = setInterval(function () {

                $("html, body").animate({ scrollTop: $(document).height() }, 20000);
                setTimeout(function () {
                    $('html, body').animate({ scrollTop: 0 }, 20000);
                }, 100);
                getData();
            }, 2000);


        });

谢谢

【讨论】:

    猜你喜欢
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 2017-02-01
    • 2017-09-17
    • 1970-01-01
    相关资源
    最近更新 更多