此脚本此后只显示一次动态内容,但不起作用。
以下是代码:
$(document).ready(function(){
$('.getmore').on('click',function(){
var last_id = $(this).attr('id');
$.ajax({
type: 'POST',
url : 'http://localhost/tech1/services/getmore.php',
data: 'last_id='+last_id,
beforeSend: function(){
$('.getmore').html('<img src="../images/loader.gif" alt="Loading..." />');
},
success: function(data){
$('.getmore').remove();
$('#comments').append(data);
}
});
});
}); 以下是完整的php代码:
<?php
mysql_connect('localhost','root','') or die('Error... Couldnt connect..');
mysql_select_db('mydb') or die('Error... Couldnt select the Db..');
$records = mysql_query(' SELECT * FROM `compare_post_comments` WHERE `post_id`=37 limit 5 ');
if(mysql_num_rows($records)){
echo '<div id="ajax_comment">';
echo '<ul id="comments">';
while($data = @mysql_fetch_array($records) ){
echo '<li>'.$data['comments'].'</li>';
$last_record = $data['sno'];
}
echo '<li class="getmore" id="'.$last_record.'">Get More</li>';
echo '</ul>';
echo "<span id='cmmnts'></span>";
echo '</div>';
}
?> getmore.php代码
<?php
if( ( isset($_POST['last_id'])!=null ) && $_POST['last_id']!="" ){
$last_id = $_POST['last_id'];
//echo "::".$last_id;
$qry = " SELECT * FROM `compare_post_comments` WHERE `post_id`=37 and sno > ".$last_id." limit 5 ";
//echo "::".$qry;
$comments = mysql_query($qry) or die('Error..');
if( mysql_num_rows($comments) ){
while( $data = mysql_fetch_array($comments) ){
echo "<li>".$data['comments']."</li>";
$last_id=$data['sno'];
}
echo "<li class='getmore' id='".$last_id."'>Get More</li>";
}else{
echo "<li class='nomore'>No More</li>";
}
}else{
echo "<li class='nomore'>No More</li>";
}?>
ajax调用只工作一次,此后就不能单击了。我对ajax和javascript知之甚少,非常感谢您的解释。
发布于 2014-01-17 09:09:32
尝试使用on的延迟语法:
$(document).on('click', '.getmore', function...这将在DOM更改中幸存下来。这个答案假定您加载的数据包含一个带有class="getmore"的对象,因为您在成功的时候将它从DOM中删除。如果不是,您需要按照remove的建议删除NewInTheBusiness,但可能需要用empty()替换它,以删除加载进度。
注意,我最近发现了只接受事件和函数的on版本的问题。在jQuery 1.10.3中,它似乎不应该开火。
发布于 2014-01-17 09:10:11
这是因为在成功之后删除getmore类。
删除这一行代码:
$('.getmore').remove();发布于 2014-01-17 09:10:45
$('.getmore').remove();Delegate到元素的static parent或document。试试看
$(document).on("click",'.getmore', function( event ) {
});https://stackoverflow.com/questions/21181794
复制相似问题