我在一个页面上有多个帖子,每个帖子都包含一个删除按钮来删除这个帖子。每个帖子都有一个独特的标识。我想使用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代码。这样我就可以在底部定义侦听器一次,所有delete按钮都会以不同的值执行该事件。
我的意思是在点击删除按钮后,它会给我发帖子的id,我会删除那个帖子。
发布于 2017-12-20 01:57:19
使用('.class')
附加事件处理程序和自定义data-*
属性来持久化任意数据,即post id,可以使用.data(key)
方法重试。
@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>
发布于 2017-12-20 02:12:30
将事件侦听器添加到每个delete按钮(取决于有多少个帖子)的替代方法是为这些帖子添加一个父容器(可能称为.posts
),将单个事件附加到该元素,并使用事件委托来捕捉按钮单击的事件,当它们在DOM上冒泡时。这叫做事件委托。
$('.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>
https://stackoverflow.com/questions/47903199
复制