使用jQuery实现点击锚点在模态框显示对应图片的问题
Hey there! I see the issue you're facing—no matter which anchor link you click, the modal always shows the first image's path. Let's fix that together!
Chances are, when setting up your click handlers or fetching the image path, you're targeting all anchor links instead of the specific one that was clicked. For example, if you use something like $('.anchor').data('img') in your click callback, that will always grab the data from the first element matching the .anchor selector, not the one you just clicked.
Here's a straightforward way to resolve this:
1. Store Image Paths in Data Attributes
When generating your dynamic anchor links, add a data-img attribute that holds the corresponding image path. This way, each link carries its own image reference directly:
// Example dynamic generation code (adjust to match your data source) const imageItems = [ { title: "Test title one", imgPath: "https://via.placeholder.com/200x150" }, { title: "Test title two", imgPath: "https://via.placeholder.com/350x250" } ]; imageItems.forEach(item => { const anchor = $(`<a href="#" class="anchor" data-img="${item.imgPath}">${item.title}</a>`); // Append the anchor to your dynamic div container $("#dynamic-content").append(anchor); });
2. Use Event Delegation & Target the Clicked Element
Since your elements are dynamically generated, use event delegation to listen for clicks. In the callback, use $(this) to reference the specific anchor that was clicked, then pull its unique data-img value:
// Handle anchor clicks with event delegation $(document).on("click", ".anchor", function(e) { e.preventDefault(); // Stop the default anchor jump behavior // Get the image path tied to the clicked anchor const targetImgPath = $(this).data("img"); // Update the modal's image source $("#modal img").attr("src", targetImgPath); // Show your modal (add your existing display logic here) $("#modal").show(); });
data-imgattributes keep each anchor's image path tied directly to the element, eliminating shared variable confusion.$(this)ensures you're only accessing data from the anchor the user actually clicked, not the first one in the DOM.- Event delegation works for dynamically added elements because it listens to events on a parent element (in this case,
document) instead of the elements themselves.
内容的提问来源于stack exchange,提问作者niceoneishere

