Ajax请求在滚动页面时加载内容
我已经尝试过但没有找到…我怎样才能改变我用on()方法编写的以下方法?
//Get old posts when scrolling down $(window).scroll(function(){ if($(window).scrollTop()==($(document).height()-$(window).height())){ //Get older posts $.ajax({ type: 'POST', url: 'action/getoldposts.php', success: function(oldposts){ //Append #postsDiv $('#postsDiv').append(oldposts); } }); } });
提前致谢!
丹尼斯
更新1
我将代码更改为以下内容,但随后在动态创建的内容没有function – 我是否缺少一些静态引用?
$(window).on('scroll',function(){ if($(window).scrollTop()==($(document).height()-$(window).height())){ //Get older posts $.ajax({ type: 'POST', url: 'action/getoldposts.php', success: function(oldposts){ //Append #postsDiv $('#postsDiv').append(oldposts); } }); } });
更新2
动态创建的元素错过了以下function:
$('#postsDiv').on('keydown', '.commenttext', function(e) { if ((e.which == 13) && !e.shiftKey) { comment($(this)); return false; } });
方法comment()如下所示:
//Function to comment on a post function comment(commenttext) { //Get postid var commenttextid=commenttext.attr('id'); var postid=commenttextid.replace("commenttext", ""); //Get commenttext var commenttext=$('#commenttext'+postid).val(); //Ajax of commenttext is not empty if(commenttext!="") { $.ajax({ type: 'POST', url: 'action/comment.php', data: 'commenttext='+commenttext+'&postid='+postid, success: function(data){ //Prepend comments $('#comments'+postid).hide().prepend( '
'+commenttext.replace( /\n/g, '
' )+'</div' ).fadeIn('slow'); //Remove from textarea what was typed in $('#commenttext'+postid).val(''); //Focus on textarea $('#commenttext'+postid).focus(); } }).error(function(){ alert('The comment could not be sent - please try again later.'); }); } else { //If the commenttext is empty, focus on the textarea nonetheless $('#commenttext'+postid).focus(); } }
注释被附加到新加载的内容,但显然错过了ajax,因为当我重新加载页面时它不再存在了。
1)几天前我做了类似的代码。 在这里,我将页面滚动事件分配给一个函数,该函数检查用户离底部多少像素。 如果用户的像素少于300或更少,则会触发loadMoreArticles()函数:
console.log()函数显示它以正确的方式实现
2)您可以在添加新内容后再次添加function。 像这样: