使用jQuery获取第一个和最后一个类

问题描述:

可能是一个新手问题。我有这样的代码行:

Might be a newbie question. I have a code line like this:

<div class="template active">

我需要自己获得每个课程。

I need to get each class for itself.

我试过这段代码:

$(this).attr("class");

从该代码我得到模板有效。我需要的是一个带有template的字符串和另一个带有active的字符串。

From that code I get "template active". What I need is one string with "template" and another with "active".

最好的jQuery函数是什么?示例?

What is the best jQuery function for that? Example?

var classes = $(this).attr("class").split(/\s/);

classes[0] === 'template'
classes[1] === 'active'

如果有两个以上的类名,你只想得到第一个&最后(这是你的问题)你可以打电话:

If there are more than two classnames and you only want to get the first & last (that was your question) you can call:

classes[0] = first class
classes[classes.length -1] = last class