选择以前缀开头并将完整类名存储为变量的类

时间:2016-03-16 14:51:13

标签: jquery

我需要根据类名开头找到一个类,然后将完整的类名添加到另一个元素。

widgets.js
<div class="slide theme-light-blue">Test</div>
<div class="result"></div>

我认为我通过使用正则表达式找到所有以“theme-”开头的类来获得第一部分,但我不知道如何将完整的类名存储为可以添加到另一个元素的变量。在此示例中,我希望将类“var theme = $('[class^="theme-"]').filter(function() { return this.className.match(/(?:^|\s)theme-/); }); $(".result").addClass(theme); ”添加到theme-light-blue div。 我在这里的代码不起作用。 请参阅fiddle here

2 个答案:

答案 0 :(得分:2)

首先你应该使用&#39;属性包含&#39; selector用于查找具有theme-*类的元素,因为它可能不一定是应用于该元素的第一个类。您对filter()的使用也是不正确的,因为它用于根据提供的过滤器减少匹配的元素集,并返回jQuery对象,而不是字符串。

要实现您的要求,您可以遍历每个classList元素的.theme-*属性,并将该类应用于页面中的下一个.result元素。试试这个:

$('[class*="theme-"]').each(function() {
    for (var i = 0; i < this.classList.length; i++) {
        if (this.classList[i].indexOf('theme-') == 0)
            $(this).next('.result').addClass(this.classList[i]);
    }    
});

Updated example

这显然假设只有一个theme-*类应用于元素。

答案 1 :(得分:0)

如果你在每种情况下都有第二堂课,那么你可以使用属性getter(split())来获得你的选择课,并用var theme = $('[class^="theme-"]').attr('class')[0].split(' ') .filter(function(a){return a.match(/(?:^|\s)theme-/) })[0]; $(".result").addClass(theme);

分开
{{1}}
相关问题