AJAX分页,页面无法点击

时间:2012-07-05 20:23:43

标签: php javascript ajax

我的ajax页面有问题。在索引文件中,我有这个分页代码:

<div id="pagesn">
<?php
    require_once 'libs/db.class.php';
    require_once 'libs/global.inc.php';
         $query="select count(*) as tot from table";
          $countset=$db->runquery($query);
          $count=$db->get_row($countset);
          $tot=$count['tot'];
          $page=1;
          $ipp=3;
          $totalpages=ceil($tot/$ipp);
          echo"<ul class='pages'>";
          for($i=1;$i<=$totalpages; $i++)
          {
              echo"<li class='$i'>$i</li>";
          }
          echo"</ul>";
        ?>
</div>

这是AJAX代码:

$("#pagesn .pages li").click(function(){
        //show the loading bar
        showLoader1();  
        $("#pagesn .pages li").css({'background-color' : ''});
        $(this).css({'background-color' : '#A5CDFA'});                
        $("#resn").load("data1.php?page=" + this.className, hideLoader1);
    });

    // by default first time this will execute
    $(".1").css({'background-color' : '#A5CDFA'});
    showLoader1();
    $("#resn").load("data1.php?page=1",hideLoader1);

主要问题是php代码在索引文件中,因此无法更新而无需刷新,因此这意味着当我添加新条目时,页码不会更新。我尝试将此代码添加到其他文件并使用jQuery加载到同一个div中:

$('#pagesn').load('data.php');

之后,页面自动更新,但随后它们变得无法点击,导致该问题的原因是什么?

3 个答案:

答案 0 :(得分:0)

当您动态添加和删除li元素时,请附加&{39; click&#39;处理程序,您需要使用.on函数:

$('#pagesn').on('click','.pages li',function(){

答案 1 :(得分:0)

尝试:

$("#pagesn").on("click",".pages li",function(){
        showLoader1();  
        $("#pagesn .pages li").css({'background-color' : ''});
        $(this).css({'background-color' : '#A5CDFA'});                
        $("#resn").load("data1.php?page=" + $(this).attr("class"), hideLoader1);
    });

答案 2 :(得分:0)

来自documentation of the .on() function

  

委托事件的优势在于它们可以处理来自稍后添加到文档的后代元素的事件。

因此,使用.on()代替.click()将确保即使在代码执行后插入的元素上也会执行处理函数。

$('#pagesn').on('click','.pages li',function(){
  // Do something ...
})