jQuery图片评论区仅首张图片可加载评论的问题求助
Hey there! I see exactly what's going wrong here—your issue boils down to global variable pollution and a misplaced selector scope. Let's break this down and fix it step by step:
What's Causing the Problem?
- Global Variables Overwriting: You're using global
idenandvaluevariables. When you click "View Comments" on the second or third image, these variables get overwritten with the wrong image's data. By the time your Ajax call finishes, it's pointing to the incorrect image container. - Wrong Selector Scope: In your
fetchingfunction,iden.find($(".paratwo")[i])is broken.$(".paratwo")[i]grabs the i-th.paratwoelement on the entire page, not just inside the current image's comment menu. Trying to find that element insideidendoesn't make logical sense.
Step-by-Step Fixes
1. Ditch Global Variables
Instead of relying on global iden and value, pass the specific menu element directly to your fetching function and use local variables inside functions. This keeps each image's comment process isolated from others.
2. Target Comments Within the Correct Container
When rendering comments, make sure you only look for .paratwo elements inside the current image's menu—not the whole page.
3. Bind Forms to Their Parent Menu
When submitting a comment, don't rely on the global iden—instead, traverse the DOM from the form to find its parent .menu container. This ensures you're updating the right image's comments.
Updated Working Code
jQuery Code
// Use a local parameter instead of global variables function fetching(menuElement) { const imageId = menuElement.data("id"); $.ajax({ url: "{% url 'fetchertwo' %}", type: "GET", data: { 'search': imageId }, dataType: 'json', success: function(data) { const comments = data.content; const authors = data.author; // Get ONLY the .paratwo elements inside this specific menu const commentElements = menuElement.find(".paratwo"); $.each(comments, function(i, commentText) { // Make sure we don't try to update an element that doesn't exist if (commentElements[i]) { $(commentElements[i]).html(`${authors[i]}: ${commentText}`); } console.log(comments[i], authors[i]); }); }, // Optional: Add error handling for better UX error: function() { menuElement.find(".paratwo").first().html("Oops, failed to load comments!"); } }); } $('.headingone').click(function(event) { event.preventDefault(); const $menu = $(this).next(); $menu.toggle("slide"); // Pass the specific menu to fetching fetching($menu); }); $('.formtwo').on("submit", function(event) { event.preventDefault(); const $form = $(this); // Find the parent menu for this form const $menu = $form.closest(".menu"); const imageId = $menu.data("id"); const formData = $form.serialize(); $.post(`/usercreation/picomment/${imageId}`, formData, function(response) { // Refresh comments for THIS menu fetching($menu); }); $form[0].reset(); });
HTML Code (No Changes Needed!)
<a style="text-decoration:blink;" href="" class="headingone" data-id={{item.pk}} >View Comments</a> <div class="menu" data-id={{item.pk}} style="display:none"> {% for i in item.piccomments.all %} <p class="paratwo" style="margin:0px;"></p> {% endfor %} <form class="formtwo" method="post" action=""> {% csrf_token %} <div class="form-group"> <div class="row"> <div class="col-6"> <input data-id={{item.pk}} autocomplete="off" type="text" name="commentadd" class="form-control commentadd" placeholder="Add Comment"> </div> <div> <input class="btn btn-outline-dark" type="submit" name="submit" value="Submit"> </div> </div> </div> </form> </div>
Bonus Tips for Better UX
- Add a loading spinner while comments are fetching (show it before the Ajax call, hide it on success/error).
- If your backend returns more comments than the template pre-renders (e.g., after adding a new comment), dynamically create new
.paratwoelements instead of relying on the initial loop. - Sanitize the comment text before rendering to prevent XSS attacks (especially if users can submit HTML).
内容的提问来源于stack exchange,提问作者Govind Shah

