如何从给定的字符串开始获取特定类的元素?

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)

http://jsfiddle.net/LQPh6/

  • @undefined:+1保持简单和正确. (3认同)

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 ...

  • 这是我所知道的,只是提供另一种选择.无论哪种方式都很好.实际上,这种方法稍微复杂一点,你可以直接获得字符串而无需操作数组. (3认同)

xyz*_*xyz 8

 // 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)

现场演示


Mar*_*cus 6

将这些值存储在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)

的jsfiddle