duanhui1185 2012-09-01 03:41
浏览 18
已采纳

初始运行后无法执行jquery post或ajax

I can't seem to make the code below work after an initial successful click. I tried both $.post and ajax to no avail. The initial click to delete any of the items work, but the succeeding clicks do not work

<script>    
$(document).ready(function(){
$('[id^="del"]').click(function(){
    var valname = $(this).attr('id').split('del_');
    /*$.post("delthis.php", {id: ""+valname[1]+""}, function(data) {
            $("#dynamic_section").html(data);
    });*/
    $("#dynamic_section").load('delthis.php', {"id":valname[1]} );
    return false;
  });
});
</script>

<body>

<div id='static_section'>This is the static section</div>
<div id='dynamic_section' style='border: 1px solid black;'>
<?php
// db connection here
$sql = mysql_query("SELECT * from test_table ORDER BY id");
while ($row = mysql_fetch_array($sql))
{
?>
<p><a href='#' id='del_<?php echo $row['id']; ?>'>Hello <?php echo $row['id']; ?></a></p>
<?php
} 
?>
</div>

This is the simple delthis.php file:

<?php
// db connection 
//$id = $_POST['id'];
$id = $_REQUEST['id'];

$sql = mysql_query("DELETE from test_table WHERE id = '$id'");

$sql = mysql_query("SELECT * from test_table ORDER BY id");
while ($row = mysql_fetch_array($sql))
   $html .= '<p><a href="#" id="del_' . $row['id'] . '">Hello ' . $row['id'] . '</a></p>';

echo $html;

?>

Appreciate any help/pointers. TIA!

  • 写回答

3条回答 默认 最新

  • doulu3865 2012-09-01 03:55
    关注

    The problem is that you replace all the content of the #dynamic_section so you have to "re-bind" the click event. Try this.

    <script>    
    $(document).ready(function(){
        function doPost(evt) {
            evt.preventDefault();
            var valname = $(this).attr('id').split('del_');
            $.post("delthis.php", {id: ""+valname[1]+""}, function(data) {
                $("#dynamic_section").html(data);
                $('[id^="del"]').click(doPost);
            });
        }
    
        $('[id^="del"]').click(doPost);
    });
    </script>
    

    Good luck!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)