使用jQuery判断锚点内图片的src是否等于指定URL
Hey Rizwi, here's how you can achieve this using jQuery when the page loads:
Check if Image SRC in .gallery_images Matches Specified URL
First, we need to wait for the DOM to be fully loaded so we can safely access the elements. Then we'll target the image inside your .gallery_images div's <a> tag and compare its src attribute to your specified URL.
Basic Implementation (Targeting the specific div with id="2")
If you only need to check the image inside that specific div with id="2", use this code:
$(document).ready(function() { // Replace this with your target URL const targetSrc = "http://v9contest.geojidesign.com/wp-content/uploads/contest_entries/thumbnail-^739D24706DC178C938623C638DDBFF0BC04ADF35338114AF68^pimgpsh_thumbnail_win_distr.jpg"; // Grab the image element const $galleryImage = $("#2 a img"); // Check for a match if ($galleryImage.attr("src") === targetSrc) { console.log("Image source matches the specified URL!"); // Add your custom logic here (e.g., show a modal, highlight the image) } else { console.log("Image source does not match."); } });
Handling Multiple .gallery_images Divs
If you have multiple .gallery_images sections and want to check all of them, use .each() to loop through each image:
$(document).ready(function() { const targetSrc = "your-target-url-here"; $(".gallery_images a img").each(function() { const $currentImg = $(this); if ($currentImg.attr("src") === targetSrc) { console.log("Matching image found!", $currentImg); // Do something with this matching image or its parent elements $currentImg.addClass("highlighted"); // Example: add a highlight class } }); });
Useful Notes
- Ensure jQuery is loaded: Make sure you've included jQuery in your page before this script runs (either via CDN or local file).
- Partial matches: If you need to check if the URL contains a specific substring instead of an exact match, use
indexOf():if ($currentImg.attr("src").indexOf("partial-url-string") !== -1) { // Partial match detected } - Case sensitivity: The strict equality (
===) is case-sensitive. If you need case-insensitive comparison, convert both strings to lowercase/uppercase first:if ($currentImg.attr("src").toLowerCase() === targetSrc.toLowerCase()) { // Case-insensitive match }
内容的提问来源于stack exchange,提问作者Rizwi
相关产品推荐
相关产品推荐

