我有一个具有多个类的元素列表,例如:
<input class="etape btn-info others">
<input class="etape btn-inverse others">
<input class="etape btn-danger others">如何编写jQuery代码,使我可以实现以下功能...
$(".etape").click(function(){
$(this).get("the class that starts with btn-")
// in order to store this value in a variable to reuse it later
});发布于 2013-03-20 01:06:01
您可以使用正则表达式或split类名。
$(".etape").click(function(){
var classes = $.grep(this.className.split(" "), function(v, i){
return v.indexOf('btn') === 0;
}).join();
});http://jsfiddle.net/LQPh6/
发布于 2013-03-20 01:34:00
您还可以尝试:
$(".etape").click(function () {
var theClass = $(this).attr("class").match(/btn[\w-]*\b/);
console.log(theClass);
});使用匹配而不是grep...
发布于 2013-03-20 00:57:55
// Only select input which have class
$('input[class]').click(function(){
var myClass;
// classNames will contain all applied classes
var classNames = $(this).attr('class').split(/\s+/);
// iterate over all class
$.each(classNames, function(index, item) {
// Find class that starts with btn-
if(item.indexOf("btn-") == 0){
// Store it
myClass = item;
}
});
});https://stackoverflow.com/questions/15505745
复制相似问题