【发布时间】:2017-05-17 13:28:15
【问题描述】:
因此,当用户在我的索引页面中滚动传递一个 div 时,我正在实现加载更多数据。
我的 div 包含数据:
<div class="container-fluid" id="post-data">
</div>
<div class="ajax-load text-center" style="display:none">
<p><img src="http://demo.itsolutionstuff.com/plugin/loader.gif">Loading More post</p>
</div>
我的 jQuery 脚本:
<script type="text/javascript">
$(document).ready(function () {
var first_id = <?php require_once 'php/functions.php'; echo get_smallest_post_id();?>;
loadMoreData(first_id);
$(document).on('scroll', function () {
if ($(this).scrollTop() >= $('#post-data').position().top) {
var last_id = $('#post-data').children('.row').last().id;
loadMoreData(last_id);
alert(last_id);
}
});
});
//Ajax load function
function loadMoreData(last_id){
$.ajax(
{
url: 'php/article.php?last_id=' + last_id,
type: "post",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
$('.ajax-load').hide();
$("#post-data").append(data);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
</script>
我的 article.php 只返回一些行:
<?php
..... (Fetch data in database)
while ($post = $select->fetch_assoc()) {
?>
<div class="row" id="<?php echo $post_id ?>">
<div class="col-sm-4"><a href="#" class=""><img src="<?php echo $first_image_src ?>" class="img-responsive"></a>
</div>
<div class="col-sm-8">
<h3 class="title"><?php echo $title ?></h3>
<p class="text-muted"><span class="glyphicon glyphicon-lock"></span> Available Exclusively for Premium
Members</p>
<p><?php echo $description ?></p>
<p class="text-muted">Presented by <a href="#"><?php echo $username ?></a></p>
<button onclick="window.location.href='https://infs3202-c25wl.uqcloud.net/travnow/content.php?id=<?php echo $post_id ?>'" id="btnReadmore" type="submit" class="btn btn-primary">Read More</button>
</div>
</div>
<hr>
<? } ?>
我的页面目前可以加载前两篇文章,但是当用户滚动通过 #post-data div 时出现问题。当我提醒 var last_id
时,它一直显示 "undefined"if ($(this).scrollTop() >= $('#post-data').position().top) {
var last_id = $('#post-data').children('.row').last().id;
alert(last_id);
}
检查结果:
我也试过了:
var last_id = $(".row:last").attr("id");
但它不起作用。
任何指针?
更新:
这实际上是一个语法错误,我的傻!感谢@SuperUser!
【问题讨论】:
-
.last().attr('id'); -
不起作用,它应该显示“5”
-
@DươngAnhKhoa 根据您的 php,您的结构需要类似于:-
<div class="container-fluid" id="1">..不是<div class="container-fluid" id="post-data">..,因为您使用了<div class="row" id="<?php echo $post_id ?>">。<?php echo $post_id ?> !==post-data。你不这么认为吗?
标签: jquery html jquery-selectors