tags:

views:

747

answers:

4

Hellou Folks!

my question: i have an img tag

<img class="myclassname" src="1.jpg" name="2.jpg">

i'd like to change the img source (currently 1.jpg) to the one i wrote in the "name" attribute (2.jpg) using jquery.

why this does not work?

$(".myclassname").attr("src", $(this).attr("name"));

thanks for any help! greets mafka

(ps: the script is more complex, of course, but this is the problem i stuck)

+3  A: 

You'll need to iterate over all tags with that classname, as $(this) is not known in that context.

Try something like:

$(".myclassname").each(function() {
    $(this).attr("src", $(this).attr("name"));
});
Daniel
i love you all!!! works perfectly, thanks
mafka
+1  A: 

I hope this helps...

  $(".test").each(function() {
   $(this).attr("src", $(this).attr("name"));
   alert($(this).attr("src"));
  });
Sohnee
Hah I beat you by 1 second!
Daniel
:) :) :) :) thx
mafka
+1 on your comment - that's funny!
Sohnee
+2  A: 
$(".myclassname").each(function (){
$(this).attr("src",$(this).attr("name"));
});

Problem with your code is that jQuery does not know what "this" in that context is.

Aviral Dasgupta
A: 

Store the reference to myclassname in a variable. Will make your script more clear to read also:

var _myClassname = $(".myclassname");
_myClassname.attr("src", _myClassname.attr("name"));
GvS