我正在尝试检查一个元素是否具有数组中的类,如果有,该类的值是多少。目前我正在使用:
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'),因为它们是元素上的多个类。
干杯
查理
最佳答案
应该执行以下操作(未经测试):
var elementClasses = $(this).attr("class").split(" ");
for(var i = 0; i < elementClasses.length; i++) {
if($.inArray(elementClasses[i], classes)) {
$thisFKeyColour = classes[i];
break;
}
}
引用:
关于javascript - jQuery - 检查元素是否具有数组中的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5232604/