我已经尝试并搜索但没有找到...如何更改我编写的以下方法以使用 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
我将代码更改为以下内容,但是动态创建的东西没有功能-我是否缺少一些静态引用?
$(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
动态创建的元素缺少以下功能:
$('#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(
'<div class="comment"><hr/>'+commenttext.replace( /\n/g, '<br/>' )+'</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,因为当我重新加载页面时它不再存在。