tags:

views:

54

answers:

1

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.

+4  A: 

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.

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