Take Url Parameter Value And Add It To Image Source With Jquery
This is going to seem a very strange question but im just playing about and i'm wondering if its at all possible. I have a page containing images all within links, I want to use jq
Solution 1:
Do it something like this: http://jsfiddle.net/qZ5AZ/1/
$("a img").attr("src", function() {
var theSrc = newRegExp("[\\?&]p=([^&#]*)").exec($(this).parent()[0].href)[1];
this.src = theSrc +".jpg";
});
And of course you really need to return the value: http://jsfiddle.net/qZ5AZ/9/
$("a img").attr("src", function() {
var theSrc = newRegExp("[\\?&]p=([^&#]*)").exec($(this).parent()[0].href)[1];
return theSrc +".jpg";
});
See more about the query string:
Solution 2:
You can target all image tags within an anchor tag by using...
$('a > img')
From there you can check each parent to see if it has the query string value you're looking for.
(/?p=([\d]+)/gi).exec(href);
All together that would be...
$('a > img').each(function(index, item) {
item = $(item);
var href = item.parent().attr('href');
var find = (/\?p=([\d]+)/gi).exec(href);
if (find) {
var number = find[1];
// Change the image src
item.attr('src', item.attr('src') + /' + number + '.jpg');
}
});
Solution 3:
Give this a try:
$('img').each(function(){
var foo = $(this).parent().attr('href').split('=');
$(this).attr('src','/'+foo[1]+'.jpg');
})
Solution 4:
You can iterate thru (using .each()
) on all $('a > img')
tag and set the src of the img tags.
DEMO here
Post a Comment for "Take Url Parameter Value And Add It To Image Source With Jquery"