dongya8378 2016-01-02 06:29
浏览 156

如何在ajax和php中动态创建按钮添加事件处理程序?

I'm developing a social networking site in which I have implemented infinite scrolling. First few elements which are not generated through ajax work fine. Next elements which are created using ajax create a problem. Here is my code in which I make an ajax call:

alert(id);
id--;
load+=1;
$.post("ajax.php",{id:id}, function(data,value){
    $(".posts").append(data);
    $('.loader').hide();            
});

and here is the code which then creates images, comments and likes button dynamically:

<?php 
while($row = $result->fetch_assoc()){
    $sql1 = "select likes from likes where pid='".$row["p_id"]."' ";
    $result1 = $link->query($sql1);
    $row1 = $result1->fetch_assoc();
?>
<img src="<?php echo $row['p_url'];?>" height="400px" width="500px" />
<p class="like" id="<?php echo $row['p_id'];?>"><?php echo $row1['likes']?></p>
<input type="button" value="like" class="btn" id="<?php echo $row['p_id'];?>" />
<input type="text" class="enter_comment  value="comments" id="comm<?php echo $row['p_id'];?>"/><input type="button" value="enter" class="cbtn" id="<?php echo $row['p_id'];?>">
<?php
}
?>

and in the same file I have created onclick event handler:

$(document).ready(function(){
    <!-- like button -->
    $(".btn").click(function(e){
        var id=$(this).attr('id');
        alert("ajax function");
        $.post("like.php",{id:id}, function(k){alert(k);});
    });
});

Now the problem is when all likes in database are 0 and I hit like button of dynamically create like button then it saves 2 likes instead of 1.

  • 写回答

1条回答 默认 最新

  • doubo1711 2016-01-02 06:41
    关注

    For this to work you need to wrap the click even in the .on() function. Anything requiring events that has been loaded via AJAX after the initial page load needs to be done like this otherwise the events don't fire.

    $('body').on('click', '.your-css-selector', function(e) {
        //perform task here
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器