【问题标题】:$(window).scrollTop() >= $(document).height() - $(window).height() - 10 Infinite Scroll not working$(window).scrollTop() >= $(document).height() - $(window).height() - 10 无限滚动不起作用
【发布时间】:2023-04-05 20:59:02
【问题描述】:

JavaScript:

$.ajax({
        type: 'POST',
        url: 'getcontent.php',
        data: 'lastid=' + 0,
        dataType: "html",
        success: function (data) {
            console.log(data);
            $("#content").append(data);
        }
    });

    $(window).scroll(function () {
        if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
            var last_id = $(".entries:last").attr("id");
            loadMoreData(last_id);
        }
    });

    function loadMoreData(last_id) {
        $.ajax({
            type: 'POST',
            url: 'getcontent.php',
            data: 'lastid=' + last_id,
            dataType: "html",
            success: function (data) {
                console.log(data);
                $("#content").append(data);
            }
        });
    }

PHP:

<?php
include_once("Medoo.php");

use Medoo\Medoo;

$database = new Medoo([
    'database_type' => 'sqlite',
    'database_file' => 'db.db'
]);

$lastid = $_POST['lastid'];
//$lastid = 10;
$lastid += 1;
$html = "";
$content = $database->select("entries", ["id", "entry"], ["id[<>]" => [$lastid, $lastid + 9]]);

for ($i = 0; $i < count($content); $i++) {
    $html .= "<p class='entries' id='" . $content[$i]["id"] . "'>" . $content[$i]["entry"] . "</p>";
}
echo $html;
?>

HTML:

<html>
<head>
<style>

p {
    width: 200px;
    height: 100px;
    background-color: aqua;
}

</style>
</head>
<body>
<div id="content"></div>
<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous">
</script>
<script src="getcontent.js"></script>
</body>
</html>

无限滚动不起作用,只要我向下滚动jQuery 就会加载所有条目,而不是只加载一个数据块。有任何想法吗? 我认为这是导致故障的原因:

$(window).scrollTop() >= $(document).height() - $(window).height() - 10

但我不确定。我尝试了不同的东西,也尝试了教程和小提琴中的东西,但没有任何效果。我的php 文件很好,它从数据库返回 10 个对象。

【问题讨论】:

  • 你有 CSS html, body { height: 100%; } 吗?我相信这对于文档高度的工作至关重要。或许可以试试$(document.body).height()。
  • 我将 if 条件替换为 document.body.offsetHeight

标签: php jquery ajax scroll infinite


【解决方案1】:

就是这样:document.body.offsetHeight

【讨论】:

    猜你喜欢
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 2013-04-22
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多