0

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 jquery to find 'X' in the location of its parent link and replace the image source with that number.

If this doesnt make sense Ive created a fiddle to try and explain things further.

I know this is a strange question and its not going to make sense, but can it be done?

http://jsfiddle.net/qZ5AZ/

Rupesh Yadav
  • 12,096
  • 4
  • 53
  • 70
Liam
  • 9,725
  • 39
  • 111
  • 209

4 Answers4

1

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');
    }
});
T. Stone
  • 19,209
  • 15
  • 69
  • 97
  • I recieve this in my console... unterminated regular expression literal [Break On This Error] item.attr('src', item.attr('src') + /' + number + '.jpg); – Liam Jan 04 '12 at 20:37
1

Give this a try:

$('img').each(function(){
        var foo = $(this).parent().attr('href').split('=');
        $(this).attr('src','/'+foo[1]+'.jpg');
})
j08691
  • 204,283
  • 31
  • 260
  • 272
1

Do it something like this: http://jsfiddle.net/qZ5AZ/1/

$("a img").attr("src", function() {
    var theSrc = new RegExp("[\\?&]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 = new RegExp("[\\?&]p=([^&#]*)").exec($(this).parent()[0].href)[1];
    return theSrc +".jpg";
});

See more about the query string:

How can I get query string values in JavaScript?

Community
  • 1
  • 1
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
1

You can iterate thru (using .each()) on all $('a > img') tag and set the src of the img tags.

DEMO here

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134