如何使用JS或jQuery修改img标签src指定字符并避免统一覆盖?
Fixing the Img SRC Replacement Overwrite Issue
Hey there, let's fix that frustrating problem where all your images ended up with the first one's src path! The root cause here is almost certainly that your original code didn't process each img element individually—instead, it grabbed the modified src from the first image and applied it to every img tag, hence the overwrite.
Here's the Correct jQuery Solution
We'll use jQuery's each() method to loop through each target image and update its src one by one:
// Target only imgs with "/image_i/" in their src to avoid unintended changes $('img[src*="/image_i/"]').each(function() { // Grab the current image's original src const originalSrc = $(this).attr('src'); // Replace "image_i" with "image_4" (adjust the number as needed) const newSrc = originalSrc.replace('/image_i/', '/image_4/'); // Update just this image's src attribute $(this).attr('src', newSrc); });
- The selector
img[src*="/image_i/"]ensures we only touch images that actually have the path segment we want to modify. - Using
each()means every image gets its own src processed and updated, no more overwriting!
If You Prefer Vanilla JavaScript (No jQuery)
No problem—here's the equivalent using plain JS:
// Get all imgs containing "/image_i/" in their src const targetImgs = document.querySelectorAll('img[src*="/image_i/"]'); // Loop through each image and update its src targetImgs.forEach(img => { const originalSrc = img.src; const newSrc = originalSrc.replace('/image_i/', '/image_4/'); img.src = newSrc; });
Quick Notes to Avoid Future Issues
- If you need to replace every instance of the letter "i" in the src (not just the one in
image_i), swap out the replace string for a global regex:originalSrc.replace(/i/g, '4'). Just be careful—this will replace any "i" in filenames or other path parts too! - Double-check your selector to make sure you're only targeting the images you intend to modify.
内容的提问来源于stack exchange,提问作者john
相关产品推荐
相关产品推荐

