如果有 class 得到 class 名字 jQuery

If has class get class name with jQuery

我有一个 div:

<div class="general_class class_1 class_2 color_ffffff"></div>

如果此 div 有一个 class 以 'color_' 开头,我需要在 jQuery 中检索整个 class 名称 'color_ffffff'变量。

var skin_color = jQuery('.general_class[class*=color_]');

在控制台日志中

console.log(skin_color);

我得到了 div 的 classes 的完整列表。

有什么想法吗? 谢谢

var skin_color = $('.general_class[class*=color_]').attr('class').split(' '); // Gets all the classes in an array

var result =  skin_color
          .filter(  function(elem){ return elem.match(/color_*/) } ) // Removes elements not matching "color_*"
          .join('') // Transforms the array (normally containing one element) to a string

alert(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="general_class class_1 class_2 color_ffffff some other classname"></div>

您可以使用正则表达式来获取颜色:

var elm = jQuery('.general_class[class*=color_]');
var re = /color_(.{6})/;
console.log(elm.attr('class').match(re));

// Yields ["color_ffffff", "ffffff"]
<div class="general_class class_1 class_2 color_ffffff"></div>