【发布时间】:2017-01-24 06:24:33
【问题描述】:
这里的按钮从数据库加载数据。工作正常。
<li class="getmore" id="'.$post_id.'"><a>Load More Posts</a></li>
如何使此按钮在向下滚动到页面底部时自动单击。简直就是无限卷轴。
我应该使用窗口滚动功能吗?如果是,那么如何在这段代码中做到这一点。
我已尝试将 ajax 代码粘贴到此函数中,但无法正常工作。
编辑: 1.当我将Ajax放入滚动函数时,getmore.php中显示mysql错误。 2. 如果我将带有点击功能的按钮类放在滚动功能中,那么它会触发太快而多次加载相同的帖子。
$(document).scroll(function(){
if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
}
});
$('body').on('click','.getmore',function(){
var lastelement = $(this ).attr('id');
$.ajax({
type : 'GET',
url : 'getmore.php',
data : 'lastelement='+lastelement,
beforesend : function(){
$('.getmore').html('loading....');
},
success: function(data){
$('.getmore').remove();
$('#recs') .append(data) ;
}
});
});
<?php
$lastelement = $_REQUEST['lastelement' ];
include("connect2.php");
if ($lastelement!=''){
$query = "SELECT * FROM `posts` "
. "WHERE (id < " . $lastelement . " AND "
. "post_keywords like '%home%') "
. "ORDER BY `posts`.`id` DESC "
. "LIMIT 10";
$records = mysql_query($query);
if (mysql_num_rows($records)) {
while($record = mysql_fetch_array($records)){
$cookie_name = 'tcVotingSystem'.$record['id'];
$post_title = $record['post_title'];
$post_id = $record['id'];
$post_date = $record['post_date'];
$post_author = $record['post_author'];
$post_image = $record['post_image'];
$post_image2 = $record['post_image2'];
$post_keywords = $record['post_keywords'];
$post_content = substr($record['post_content'],0,100);
?>
<div>
//posts goes here
</div>
【问题讨论】:
-
为什么你要通过
$('.getmore').remove();删除ajax成功的加载按钮? -
因为在getmore.php里面,同样的按钮又出现在了底部。
-
还有什么问题要放 $('.getmore').click();在你的 JS 滚动条件函数里面?
-
@Daniel 问题是它会触发多次。每个帖子都会出现 2-3 次。快速滚动时,它会加载相同的帖子甚至超过 5 次。完美的唯一方法是超级慢地滚动。如果可以阻止多起火灾,那么它将对我有用
-
获取最后一个帖子 ID 是否可靠,在 AJAX 成功上设置为查询的初始偏移量,并为您在每个 beforeSend 操作上增加一些帖子计数器?不加载重复项看起来更可预测和更简单。
标签: javascript jquery ajax