doupai6875 2018-01-29 12:36
浏览 507
已采纳

在动态生成的php按钮上绑定事件

I have a simple table that manages a list of user created posts. Inside the table, I have two buttons that are supposed to manage the edit or the deletion of the single posts.

I have a problem with these buttons, when I try to edit one entry that isn't the first one listed, no actions occur. How i can manage this? I know that every button need an unique id, but i can't figure out how to fix this because the buttons are dynamically generated with a php for() loop.

<tbody>
    <? for($n=0;$n<count($load);$n++): ?>
    <tr>
    <th scope="row"><? echo $n; ?></th>
        <td class="postListTitle"><? echo $load[$n]['post_title']; ?></td>
        <td id="postListDate"><? echo $load[$n]['post_date']; ?></td>
        <td class="button-group"><button class="btn btn-warning btn-sm" id="btn-edit-post">Edit</button><button class="btn btn-danger btn-sm" id="btn-delete-post">Delete</button></td>
    </tr>
    <? endfor; ?>
</tbody>

Jquery code:

$('#btn-edit-post').on('click',function(e){
    e.preventDefault();
    var postTitle = $('.postListTitle').html();

    $.ajax({
        url:'system/ajax/doPost.php?title='+encodeURIComponent(postTitle),
        type:'GET',
        cache: false,
        success: function(item){
            var post = JSON.parse(item);

            $('#edit-title').attr('value',post.title);
            $('#edit-text').append(post.text);
        }
    });
});
  • 写回答

2条回答 默认 最新

  • dongqiang5541 2018-01-29 12:55
    关注

    First thing you need to understand is that all your button have the same ID which is btn-edit-post and btn-delete-post an ID attribute must be unique, therefore you need to create the ID's dynamically.Like this

    <button class="btn btn-warning btn-sm" id="edit_<?=$load[$n]['post_id']?>">Edit</button>
    <button class="btn btn-danger btn-sm" id="delete_<?=$load[$n]['post_id']?>">Delete</button></td>
    

    See the ID is dynamically for the edit make the id edit_(PoSTID) for the delete make it delete_(POSTID)

    Then on your jquery

    <script type="text/javascript">
                $('[id^="edit_"]').on('click',function(){
                var id = $(this).attr('id').split("_")[1]; //get the post ID
    
                //continue what you need.
    
            });
            </script>
    

    delete

    <script type="text/javascript">
                $('[id^="delete_"]').on('click',function(){
                var id = $(this).attr('id').split("_")[1]; //get the post ID
    
                //continue what you need.
    
            });
            </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题