jQuery获取类名

jQuery获取类名,jquery,Jquery,我试图在单击时从选定的图像中获取类名 下面的代码检索第一个images类名称,但当我单击具有不同类值的其他图像时,它们会显示第一个images类 如何获取每个图像类的值 HTML 尝试: 经过深思熟虑,上述情况可能并不完全是你所追求的。我建议试试: $('.bg img').click( // attaches the 'click' to the image function(){ var1 = $(this).attr('class'); }); 或: 请

我试图在单击时从选定的图像中获取类名

下面的代码检索第一个images类名称,但当我单击具有不同类值的其他图像时,它们会显示第一个images类

如何获取每个图像类的值

HTML

尝试:

经过深思熟虑,上述情况可能并不完全是你所追求的。我建议试试:

$('.bg img').click(  // attaches the 'click' to the image
    function(){
        var1 = $(this).attr('class');
    });
或:

请尝试以下方法:

$(".bg").click(function(){
    var1 = $(this).children('img').attr('class');

感谢您的回复,但这将给我链接中的类值,而不是图像。@Jemes,虽然第一个代码部分将返回
a
class
名称,但后两个代码示例将返回图像的
class
;特别是这三种方法中的最后一种,可以根据您的需要工作。谢谢您的帮助,效果非常好。我还发现var1=$('img',this.attr('class');同样有效,但使用哪种方法更好?两者都同样有效-在您的案例中,$('img',this)可能更好。但是,如果您已经设置了上下文,那么您将需要对其调用or.find()。@Jemes和@fx\ux:顺便使用
$('img',this)
会导致jQuery在内部调用
$(this.find('img')
:这意味着后者稍微快一点(尽管是微优化)。
$(".bg").click(function(){
    var1 = $(this).attr('class');
});
$('.bg img').click(  // attaches the 'click' to the image
    function(){
        var1 = $(this).attr('class');
    });
$(".bg").click(function(){
    var1 = $(this).find('img').attr('class'); // finds the 'img' inside the 'a'
});
$(".bg").click(function(){
    var1 = $(this).children('img').attr('class');