jQuery 获取类名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5338678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Get Class Name
提问by Jemes
I'm trying to get the class name from an selection of images when clicked.
我试图在单击时从一组图像中获取类名。
The code below retrieves the first images class name but when I click on my other images with different class values they display the first images class.
下面的代码检索第一个图像类名称,但是当我单击具有不同类值的其他图像时,它们显示第一个图像类。
How can I get each images class value?
如何获取每个图像类值?
HTML
HTML
<a href="#" title="{title}" class="bg"><img src="{image:url:small}" alt="{title}" class="{image:url:large}" /></a>
jQuery Code
jQuery 代码
$(".bg").click(function(){
var1 = $('.bg img').attr('class');
回答by fx_
Try this instead:
试试这个:
$(".bg").click(function(){
var1 = $(this).children('img').attr('class');
回答by David says reinstate Monica
Try:
尝试:
$(".bg").click(function(){
var1 = $(this).attr('class');
});
The above might, on reflection, not be quite what you're after. I'd suggest trying:
以上可能,经过反思,并不是你所追求的。我建议尝试:
$('.bg img').click( // attaches the 'click' to the image
function(){
var1 = $(this).attr('class');
});
Or:
或者:
$(".bg").click(function(){
var1 = $(this).find('img').attr('class'); // finds the 'img' inside the 'a'
});