Estoy tratando de verificar si un elemento tiene una clase de una matriz y, de ser así, cuál es el valor de esa clase. Por el momento solo estoy usando:jQuery - Comprobar si el elemento tiene una clase de una matriz
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);
¿Hay una mejor manera de hacerlo? Algo así como:
if (in_array(classes, element.attr('class'))) {
$thisFKeyColour = Class_Of_Element_That_Matched_Array;
}
Además, no puedo simplemente devolver el .attr ('clase') ya que hay múltiples clases sobre el elemento.
Saludos
Charlie
¿Qué tal un bucle foreach en una matriz de posibles nombres de clase, asigne su valor y rompa si es verdadero. – Lazarus
Lo intentaré y veré lo que obtengo. Gracias :) –
posible duplicado de [jQuery hasClass() - verifique para más de una clase] (http://stackoverflow.com/questions/2214952/jquery-hasclass-check-for-more-than-one-class) –