循环列表中点击指定删除图标时显示对应加载器的问题排查
Hey there! Let's break down why your current setup isn't working as expected and get it sorted out step by step.
What's Causing the Issue?
Duplicate IDs Break Uniqueness
You're usingid="deletefile"for every span in your loop, but HTML requires IDs to be unique across the entire page. Browsers only ever target the first element with a given ID, which is why only the first loader triggered after your modification.Selector Targets the Wrong Element
Your original jQuery uses$('#deletefile')to find the loader. This always grabs the first element with that ID, not the specific delete button you actually clicked.
The Solution
Let's adjust both your HTML and jQuery to work seamlessly with looped elements:
Step 1: Update the HTML (Use Classes Instead of IDs)
Replace the unique ID with a reusable class for your delete spans—classes are designed to be used multiple times:
<span class="deletefile"> <i class="fas fa-trash-alt"></i> <div class='loader' style='display:none'></div> </span>
Step 2: Modify jQuery to Target the Clicked Element
Use $(this) to reference the exact delete span that was clicked, then find its nested loader:
$('span.deletefile').click(function() { // $(this) refers to the specific delete span you just clicked $(this).find('.loader').show(); });
Bonus: Handling AJAX Cleanup
If you're using this with an AJAX delete request, keep track of the clicked element to hide the loader once the request completes (success or failure):
$('span.deletefile').click(function() { const $currentDeleteBtn = $(this); $currentDeleteBtn.find('.loader').show(); // Example AJAX delete call $.ajax({ url: '/your-delete-endpoint', method: 'DELETE', data: { /* Pass your file ID or relevant data here */ }, success: function() { // Hide the loader or remove the entire list item $currentDeleteBtn.find('.loader').hide(); // Optional: Remove the list entry entirely $currentDeleteBtn.closest('.list-item').remove(); }, error: function() { // Don't forget to hide the loader if the request fails! $currentDeleteBtn.find('.loader').hide(); } }); });
This setup ensures every delete button only triggers its own loader, no matter how many items you render in your loop.
内容的提问来源于stack exchange,提问作者Sreedevi

