fat*_*Dev 28 html css jquery twitter-bootstrap
我有一个包含多个类的元素列表,例如:
<input class="etape btn-info others">
<input class="etape btn-inverse others">
<input class="etape btn-danger others">
Run Code Online (Sandbox Code Playgroud)
如何编写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
});
Run Code Online (Sandbox Code Playgroud)
und*_*ned 50
您可以使用正则表达式或split类名.
$(".etape").click(function(){
var classes = $.grep(this.className.split(" "), function(v, i){
return v.indexOf('btn') === 0;
}).join();
});
Run Code Online (Sandbox Code Playgroud)
Mar*_*det 17
你也可以尝试:
$(".etape").click(function () {
var theClass = $(this).attr("class").match(/btn[\w-]*\b/);
console.log(theClass);
});
Run Code Online (Sandbox Code Playgroud)
使用匹配而不是grep ...
// 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;
}
});
});
Run Code Online (Sandbox Code Playgroud)
将这些值存储在data属性中可能更好:
<input class="etape others" data-btntype="info">
<input class="etape others" data-btntype="inverse">
<input class="etape others" data-btntype="danger">
Run Code Online (Sandbox Code Playgroud)
然后:
$(".etape").click(function(){
var myBtnType = $(this).data('btntype');
});
Run Code Online (Sandbox Code Playgroud)