多个html元素针对单个js事件

问题描述 投票:0回答:2

我在一个页面上有多个帖子,每个帖子都包含一个用于删除帖子的删除按钮。每个帖子都有一个唯一的ID。我想用ajax删除帖子。

所以,我需要为每个帖子创建不同的jquery事件监听器。

这是实际上,我正在做的事情:

@foreach($posts as $post)
    <h1>$post->some_field</h1>
    <a href="#" id="deletePost{{$post->id}}">delete</a>

    <script>
        $('#deletePost{{$post->id}}').on('click', function(){
            // create confirm dialog
            // delete the post with id {{$post->id}}
        })
    </script>
@endforeach

为每个帖子创建了javascript代码。有没有办法,所以我可以在底部定义一次监听器,所有删除按钮用不同的值执行该事件。

我的意思是在点击删除按钮后,它会给我帖子的ID,我将删除该帖子。

javascript jquery html ajax
2个回答
4
投票

使用Class Selector ('.class')附加事件处理程序和自定义data-*属性来保存任意数据,即可以使用.data(key)方法重试的post id。

@foreach($posts as $post)
    <h1>$post->some_field</h1>
    <a href="#" data-id="{{$post->id}}" class="deletePost">delete</a>
@endforeach

<script>
    $('.deletePost').on('click', function(){
        // delete the post with id {{$post->id}}
        var postId = $(this).data('id')
    })
</script>

2
投票

为每个删除按钮添加事件监听器(取决于有多少帖子)的替代方法是为帖子添加父容器,可能称为.posts,将单个事件附加到该元素,并使用事件委派来捕获来自按钮点击它们冒泡DOM。这叫做event delegation

$('.posts').on('click', '.delete', function() {
  const $post = $(this).parent();
  const id = $post.data('id');
  console.log(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="posts">
  <article data-id="1">
    <button class="delete">Delete</button>
  </article>
  <article data-id="2">
    <button class="delete">Delete</button>
  </article>
  <article data-id="3">
    <button class="delete">Delete</button>
  </article>
</section>
© www.soinside.com 2019 - 2024. All rights reserved.