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



我有一个简单的表格来管理用户创建的帖子列表。在表格中,我有两个按钮,用于管理单个帖子的编辑或删除。

我的这些按钮有问题,当我尝试编辑一个不是列出的第一个条目时,没有发生任何操作。我该如何管理?我知道每个按钮都需要一个唯一的 id,但我无法弄清楚如何解决这个问题,因为这些按钮是使用 php for() 循环动态生成的。

<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代码:

$('#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);
        }
    });
});
您需要

了解的第一件事是,所有按钮都具有相同的 ID btn-edit-post并且btn-delete-post ID 属性必须是唯一的,因此您需要动态创建 ID。喜欢这个

<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>

查看 ID 是动态的编辑使 id edit_(PoSTID( 用于删除使其delete_(POSTID(

然后在你的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>

删除

<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>

您需要将选择器绑定到静态元素。

$(document).on('click','#btn-edit-post', function(e){
    ...
});

我也同意评论,如果您有多行按钮共享相同的 id,您最好切换到使用 class。

最新更新