开发者

jQuery getting class

开发者 https://www.devze.com 2023-01-03 07:00 出处:网络
$(document).ready(function(){ $(\'img\').click(function(){ var class = $(\"img\").attr(\"class\"); console.log(class);
            $(document).ready(function(){

      $('img').click(function(){
 var class = $("img").attr("class");
 console.log(class);
      });

            });

Back with another question. I have 3 images each with a different class (image1, image2, image3). If i run the code ab开发者_JAVA技巧ove the log will only show the class of the first image no matter what image I click on


Within your click event handler, replace $("img") with $(this)

like:

$('img').click(function(){ 
   var class = $(this).attr("class"); 
   console.log(class); 
}); 

this will reference to the specific object which is involved. You may also use the event.target like $(event.target).attr("class");, if you declare event as parameter of your click handler.


Use $(this) inside the click event to get the current object.

$('img').click(function(){ 
    var class = $(this).attr("class"); 
    console.log(class); 
}); 
0

精彩评论

暂无评论...
验证码 换一张
取 消