我试图检查一个元素是否有一个数组中的类,如果有的话,那个类的值是什么。目前我正在使用:jQuery - 检查元素是否有数组中的类?
if ($(this).hasClass('purple_grad')) {
$thisFKeyColour = 'purple_grad';
} else if ($(this).hasClass('red_grad')) {
$thisFKeyColour = 'red_grad';
} else if ($(this).hasClass('green_grad')) {
$thisFKeyColour = 'green_grad';
} else if ($(this).hasClass('blue_grad')) {
$thisFKeyColour = 'blue_grad';
} else if ($(this).hasClass('yellow_grad')) {
$thisFKeyColour = 'yellow_grad';
} else if ($(this).hasClass('light_yellow_grad')) {
$thisFKeyColour = 'light_yellow_grad';
} else if ($(this).hasClass('lighter_yellow_grad')) {
$thisFKeyColour = 'lighter_yellow_grad';
} else if ($(this).hasClass('grey_grad')) {
$thisFKeyColour = 'grey_grad';
} else if ($(this).hasClass('light_grey_grad')) {
$thisFKeyColour = 'light_grey_grad';
} else if ($(this).hasClass('black_grad')) {
$thisFKeyColour = 'black_grad';
}
}
alert($thisFKeyColour);
有没有更好的方法来做到这一点?就像:
if (in_array(classes, element.attr('class'))) {
$thisFKeyColour = Class_Of_Element_That_Matched_Array;
}
另外,我不能只返回.attr('类'),因为它们是元素上的多个类。
干杯
查理
对于可能的类名称数组上的foreach循环怎么样,如果为true,则分配您的值并中断。 – Lazarus 2011-03-08 12:46:32
我试试看看我得到了什么。谢谢:) – 2011-03-08 12:51:52
可能重复的[jQuery hasClass() - 检查多个类](http://stackoverflow.com/questions/2214952/jquery-hasclass-check-for-more-than-one-class) – 2015-05-08 09:10:24