【问题标题】:get jquery class name starting with some letter获取以某个字母开头的 jquery 类名
【发布时间】:2018-03-27 01:12:18
【问题描述】:

我有一个这样的 html,我需要获取以“border_”之类的字母开头的类名

<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

【问题讨论】:

  • 请不要忘记通过单击答案左上方的复选标记将任何对您有帮助的答案标记为已接受的答案

标签: jquery each classname


【解决方案1】:

如果您想要一个相当简单的版本,只需使用数组、映射和一个不错的正则表达式,试试这个;

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(),然后在循环内使用el.className.match() 结果执行一些jQuery 工作:)

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

JSFiddle with results, here

【讨论】:

    【解决方案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-”

    【讨论】:

      【解决方案3】:

      通过过滤掉不匹配的来收集它们

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

      【讨论】:

        猜你喜欢
        • 2012-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-02
        • 2023-03-26
        • 2018-02-09
        • 1970-01-01
        相关资源
        最近更新 更多