jquery ajax加载带有多个实例的更多按钮

时间:2015-09-30 00:55:11

标签: jquery ajax

如何在同一页面上多次使用此代码?

我正在显示将使用ajax抓取的数据,每个数据都有自己的评论框和“显示更多评论”按钮。

就像我按下“显示更多评论”按钮一样,每个评论框都会更新 - 而不是点击的评论框。

我想我需要修改Jquery / ajax代码:

$( document ).on( 'click', '.loadmore', function () {
     $(this).text('Loading...');
     var ele = $(this).parent('li');
      $.ajax({
        url: 'loadmore.php',
        type: 'POST',
        data: {
          page:$(this).data('page'),
        },
        success: function(response){
          if(response){
            ele.hide();
            $(".news_list").append(response);
          }
        }
      });
});

HTML / PHP:

<div id="container">
<ul class="news_list">
<?php
$query=mysql_query("SELECT * FROM `comments` ORDER BY `id` ASC LIMIT 0 , $resultsPerPage");
while($data=mysql_fetch_array($query)){
$title=$data['name'];
$content=$data['comment'];
echo "<li><h3>$title</h3><p>$content<p></li>";
}
?>
<li class="loadbutton"><button class="loadmore" data-page="2">Load More</button></li>
</ul>
</div>

loadmore.php:

    <?php include('config.php'); ?>
    <?php
        if(isset($_POST['page'])):
        $paged=$_POST['page'];
        $sql="SELECT * FROM `comments`ORDER BY `id` ASC";
        if($paged>0){
               $page_limit=$resultsPerPage*($paged-1);
               $pagination_sql=" LIMIT  $page_limit, $resultsPerPage";
               }
        else{
        $pagination_sql=" LIMIT 0 , $resultsPerPage";
        }

        $result=mysql_query($sql.$pagination_sql);

        $num_rows = mysql_num_rows($result);
        if($num_rows>0){
        while($data=mysql_fetch_array($result)){
        $title=$data['name'];
        $content=$data['comment'];
        echo "<li><h3>$title</h3><p>$content<p></li>";
        }
        }
        if($num_rows == $resultsPerPage){?>
        <li class="loadbutton"><button class="loadmore" data-page="<?php echo  $paged+1 ;?>">Load More</button></li>
     <?php 
      }else{
        echo

 "<li class='loadbutton'><h3>No More Feeds</h3></li>";
 }
  endif;
   ?>

有什么建议吗?

问候

1 个答案:

答案 0 :(得分:0)

对于每个实例,更改按钮的类和将显示内容的div。例如loa dmore按钮应该有以下类

<li class="loadbutton1"><button class="loadmore1" data-page="2">Load More</button></li>

<li class="loadbutton2"><button class="loadmore2" data-page="2">Load More</button></li>

<li class="loadbutton3"><button class="loadmore3" data-page="2">Load More</button></li>