JQuery点击.trigger触发进度条动画失效问题求助
Hey there! Let's figure out why your progress bar animation breaks when using $(this).closest(".item")—I’ve run into similar selector scope issues before, so let’s break this down.
The Core Issue: Selector Scope & Targeting
From your code snippet, the problem likely comes down to which progress bar you’re targeting. When you use $(".progressbar") directly, you’re selecting all progress bars on the page. Without closest(), this might have worked if you only had one progress bar, but now that you’re working with a list of .item elements, you need to target only the progress bar inside the clicked item’s container.
Here’s the breakdown of what’s going wrong:
- You correctly grab the parent
.itemwith$(this).closest(".item"), but then you ignore that container when updating the progress bar—you still target every.progressbarglobally. - If your animation is tied to a specific progress bar instance (like a plugin that initializes on page load), updating a global selector won’t trigger the animation on the correct bar.
- Bonus red flag: Using
#percentas a selector is risky—IDs must be unique on a page. If you have multiple.itemelements, this will cause unexpected behavior when usingfind("#percent").
Fixed Code Example
Let’s adjust your code to target only the elements inside the clicked .item, fix the ID issue, and ensure the animation triggers on the correct progress bar:
$(".list").on("click", ".trigger", function() { // Grab the parent item container for the clicked trigger const $currentItem = $(this).closest(".item"); // Use a class instead of ID for percentage (avoids duplicate ID issues) const percentageValue = $currentItem.find(".percent").text(); // Target ONLY the progress bar inside the current item const $targetProgressbar = $currentItem.find(".progressbar"); // Update the data attribute on the correct progress bar $targetProgressbar.attr("data-percentage", percentageValue); // Trigger the animation on the targeted progress bar // Replace this with your actual animation method (e.g., plugin update or custom animate) $targetProgressbar.animate({ width: `${percentageValue}%` }, 800); return false; // Prevent default click behavior if needed });
Key Fixes Explained
- Scope targeting: By using
$currentItem.find(".progressbar"), you ensure you’re only modifying the progress bar that belongs to the clicked item. - Unique selectors: Swapping
#percentfor.percentfixes the duplicate ID problem, which could have been silently breaking element selection. - Animation specificity: Triggering the animation on the targeted progress bar (instead of all progress bars) ensures the animation runs on the correct element.
If you’re using a third-party progress bar plugin, you might need to call its specific update method instead of a generic animate()—for example, if using ProgressBar.js, you’d use something like $targetProgressbar.data("progressbar").update(parseInt(percentageValue)).
内容的提问来源于stack exchange,提问作者Kyle Underhill

