2

I want a function that replace each li with an image. This is my code:

$(document).ready(function(){
    var tmphref;
    var tmpname;
    var str = '<a href="' + tmphref + '"><img src="http://www.somesite.com/a/' + tmpname[1] + '/avatar-small.jpg /></a>';
    $('#somediv li a').each(function(){
        tmphref = $(this).attr("href");
        tmpname = /http\:\/\/(\w+)\.somesite\.com\//.exec(tmphref);
        $(this).parent().replaceWith(str);
    });
});

The image is in this specific path: www.somesite.com/a/username/avatar-small.jpg
The code above doesn't work. Any ideas?

Thank you in advance.

1 Answer 1

4

Move

var str = '<a href="' + tmphref + '"><img src="http://www.somesite.com/a/' + tmpname[1] + '/avatar-small.jpg /></a>';

after tmphref and tmpname, like this

$('#somediv li a').each(function(){
    tmphref = $(this).attr("href");
    tmpname = /http\:\/\/(\w+)\.somesite\.com\//.exec(tmphref);
    var str = '<a href="' + tmphref + '"><img src="http://www.somesite.com/a/' + tmpname[1] + '/avatar-small.jpg /></a>';
    $(this).parent().replaceWith(str);
});

because variable str is already assigned values with undefined tmphref, and tmpname, so changing the values of tmphref and tmpname after that, wouldn't effect the variable str

And, for that case, you don't need to declare variable for tmphref and tmpname outside .each function.

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

3 Comments

Exactly - you're setting the two variables after you're using them. :)
That came into my mind, but isn't that declaring a new variable for every li? (it has the var keyword)
Warrantica, your tmphref is based on the each loop, so its needed to do it inside.

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.