gpt4 book ai didi

javascript - jQuery - 检查元素是否具有数组中的类?

转载 作者:太空狗 更新时间:2023-10-29 13:20:13 26 4
gpt4 key购买 nike

我正在尝试检查一个元素是否具有数组中的类,如果有,该类的值是多少。目前我正在使用:

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;
}
}

Try it out here.

引用:

http://api.jquery.com/jQuery.inArray/

关于javascript - jQuery - 检查元素是否具有数组中的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5232604/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com