JQuery: Replace strings with .each ()

I need a function that replaces 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 particular path: www.somesite.com/a/username/avatar-small.jpg
The above code doesn't work. Any ideas?

Thanks in advance.

+2


a source to share


1 answer


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

      

since the variable is str

already assigned to the values ​​with undefined

tmphref

and tmpname

, therefore changing the values tmphref

and tmpname

afterwards will not affect the variablestr

And in this case, you don't need to declare a variable for tmphref

and tmpname

outside .each

.

+4


a source







All Articles