I would like to c...">

JQuery: use "name" as img "src"

my question: I have an img tag

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

      

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

why doesn't it work?

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

      

thanks for any help! hails mafka

(ps: the script is of course more complicated, but this is the problem I'm stuck with)

+2


source to share


4 answers


You will need to iterate over all tags with this class name, since $ (this) is unknown in this context.

Try something like:



$(".myclassname").each(function() {
    $(this).attr("src", $(this).attr("name"));
});

      

+4


source


$(".myclassname").each(function (){
$(this).attr("src",$(this).attr("name"));
});

      



The problem with your code is that jQuery doesn't know what "this" is in this context.

+2


source


Hope this helps ...

        $(".test").each(function() {
            $(this).attr("src", $(this).attr("name"));
            alert($(this).attr("src"));
        });

      

+1


source


Store the reference to myclassname in a variable. Let's make your script more readable:

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

      

0


source







All Articles