2017-10-15 49 views
0

我有一个HTML这样我需要得到的类名称开头,如“border_”GET jQuery的类名称以一些字母

<div class="box selected border_red"></div> 

<div class="box selected border_blue"></div> 

<div class="box border_pink inactive"></div> 

<div class="box selected border_green"></div> 

<div class="box border_grey inactive"></div> 

jquery 

$('.box').each(function(){ 

}) 

出需要

border_red 

border_blue 

border_pink 

border_green 

border_grey 
+0

请不要”通过点击答案左上方的复选标记,忘记标记任何可以帮助您作为接受答案的答案 –

回答

1

收集放一些字母他们都过滤掉那些不匹配

var classes = []; 
$('.box').each(function() { 
    classes = classes 
     .concat(
      $(this).attr("class") 
       .split(' ') 
       .filter(function(cls) {cls.indexOf('border_') === 0}) 
     ); 
}) 
2

var check = "border_"; 
 
$('div.box[class*="border_"]').each(function() {  
 
     // Get array of class names 
 
     var cls = $(this).attr('class').split(' ');  
 
     for (var i = 0; i < cls.length; i++) { 
 
      // Iterate over the class and log it if it matches 
 
      if (cls[i].indexOf(check) > -1) {   
 
       console.log(cls[i].slice(0, cls[i].length)); 
 
      }  
 
     }  
 
    });
.box{ 
 
width:100px; 
 
height:100px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="box selected border_red"></div> 
 

 
<div class="box selected border_blue"></div> 
 

 
<div class="box border_pink inactive"></div> 
 

 
<div class="box selected border_green"></div> 
 

 
<div class="box border_grey inactive"></div>

这个问题的启发:JQuery get the rest of the element's class name that starts with string “whatever-”

0

如果你想一个相当简单的版本,只需使用数组,地图和一个漂亮的正则表达式试试这个;

var borders = 
    $(".box") 
    .toArray() 
    .map(function(el) { 
     return el.className.match(/\b(border_[a-z0-9]+)\b/gi)[0]; 
    }); 

// "borders" is an array 
console.log(borders); 

你也可以决定改变.map().each()然后做环内的一些jQuery的工作与el.className.match()结果:)

$(".box") 
    .each(function(key,el) { 
    $(el).text(el.className.match(/\b(border_[a-z0-9]+)\b/gi)[0]); 
    }); 

JSFiddle with results, here

相关问题