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/

4 Answers 4

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?

Sign up to request clarification or add additional context in comments.

Comments

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');
    }
});

1 Comment

I recieve this in my console... unterminated regular expression literal [Break On This Error] item.attr('src', item.attr('src') + /' + number + '.jpg);
1

Give this a try:

$('img').each(function(){
        var foo = $(this).parent().attr('href').split('=');
        $(this).attr('src','/'+foo[1]+'.jpg');
})

Comments

1

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

DEMO here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.