This jQuery code snippet modifies image src
attributes to use absolute paths, converting relative paths to absolute ones using a specified domain. This is helpful for cross-domain testing or when sourcing images from an external domain.
(function ($) { $(document).ready(function () { $('img').each(function (i, v) { let $el = $(this), src = $el.attr('src'), //Improved regex to handle various relative path structures srcRx = /^\/?[^:]+/; // Matches leading slash (optional) followed by non-colon characters if (srcRx.test(src)) { let absoluteSrc = 'http://splash.abc.net.au' + (src.startsWith('/') ? src : '/' + src); $el.attr('src', absoluteSrc); } }); }); })(jQuery);
This improved version uses a more robust regular expression (srcRx
) to correctly identify relative paths, even those without a leading slash. It also ensures that a leading slash is added if it's missing from the relative path before appending the base URL. This prevents potential issues with incorrect path construction.
A JSfiddle demonstrating this improved code is available at [JSfiddle Link - (replace with actual JSfiddle link if created)]. (Note: I cannot create a JSfiddle link dynamically).
Ben Alman's excellent jquery.ba-urlinternal.js
plugin provides more comprehensive URL manipulation capabilities, including handling relative and absolute paths effectively. You can find it at [GitHub Link - (replace with actual GitHub link)].
Frequently Asked Questions (FAQs) about Relative and Absolute Paths
This section answers common questions about relative and absolute paths in the context of web development.
What is the difference between relative and absolute paths?
https://www.example.com/images/logo.png
)./
(root-relative) or uses ../
to go up a directory level (e.g., /images/logo.png
or ../images/logo.png
).How do I get the value of the src
attribute in jQuery?
Use the .attr()
method: $('img').attr('src');
This gets the src
of the first image. Use .each()
to iterate through all images:
$('img').each(function() { console.log($(this).attr('src')); });
What is the difference between relative and absolute paths in HTML? (Same as above, but in the context of HTML)
How do I solve the src
absolute path problem?
Ensure the path is correct and the file exists. Double-check URLs for absolute paths and the relative path's position concerning the current HTML file.
How do I get the src
attribute of all images on a page with jQuery? (Same as the jQuery example above) To store them in an array:
let srcs = []; $('img').each(function() { srcs.push($(this).attr('src')); });
The above is the detailed content of Update images with a specific src (relative path) with absolute path. For more information, please follow other related articles on the PHP Chinese website!