【发布时间】:2011-07-11 02:18:08
【问题描述】:
我试图检查一个元素是否具有来自数组的类,如果是,那么该类的值是什么。目前我只是在使用:
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('class') 因为它们是元素上的多个类。
干杯
查理
【问题讨论】:
-
在一个可能的类名数组上的 foreach 循环怎么样,分配你的值,如果为真则中断。
-
我会试试看我得到了什么。谢谢:)
标签: javascript jquery html class dom