如何通过src属性查找指定img标签并添加nopin属性?
Hey there, I’ve got you covered with a straightforward solution to add the nopin="nopin" attribute to your target images using their src values—no IDs or classes needed!
src Attribute jQuery Method (Since you mentioned jQuery)
The key here is using jQuery's attribute equals selector to pick out exactly the images with your specified src URLs. Wrap the code in a document-ready handler to make sure it runs only after all page elements are loaded (so your images exist when we try to modify them):
$(function() { // Add nopin to image-3.jpg $('img[src="https://example.com/image-3.jpg"]').attr('nopin', 'nopin'); // Add nopin to image-5.jpg $('img[src="https://example.com/image-5.jpg"]').attr('nopin', 'nopin'); });
Breakdown:
$(function() { ... })is shorthand for$(document).ready()—this ensures we don’t try to select images before they’re rendered in the DOM.img[src="exact-url"]targets only<img>tags where thesrcattribute matches the exact string you provide (no partial matches here, which is exactly what you need)..attr('nopin', 'nopin')adds the required attribute to each selected image.
Native JavaScript Alternative (No jQuery)
If you’d rather skip jQuery, here’s the vanilla JS version that does the same thing:
document.addEventListener('DOMContentLoaded', function() { // Target image-3.jpg and add the attribute const img3 = document.querySelector('img[src="https://example.com/image-3.jpg"]'); if (img3) img3.setAttribute('nopin', 'nopin'); // Target image-5.jpg and add the attribute const img5 = document.querySelector('img[src="https://example.com/image-5.jpg"]'); if (img5) img5.setAttribute('nopin', 'nopin'); // If you have multiple images with the same src, use querySelectorAll + forEach: // document.querySelectorAll('img[src="https://example.com/image-3.jpg"]').forEach(img => img.setAttribute('nopin', 'nopin')); });
What the Final HTML Looks Like
After running either code, your target images will have the nopin attribute added, just like this:
<img src="https://example.com/image-3.jpg" nopin="nopin" alt="..."><img src="https://example.com/image-5.jpg" nopin="nopin" alt="...">
内容的提问来源于stack exchange,提问作者Frank

