jQuery使用部分字符串查找完整的类名

时间:2015-08-22 11:42:57

标签: jquery class

我有不同类名'in-left' 'in-right' 'in-bottom'等的幻灯片。我需要先找到任何一个以'in-'开头的课程的幻灯片,但我需要获得完整的课程名称' in-left'用于switch语句。我试图找到最有效的方法,希望没有正则表达式?

通常我会使用数据属性data-in="left",但不能用于此项目。

<div class="container">
    <div class="slide in-left"></div>
    <div class="slide in-right"></div>
    <div class="slide in-bottom"></div>
    <div class="slide in-top"></div>
</div>

jquery的

var $els = $('.slide[class*="in-"]');
$.each( $els, function(k, v){
  var type = v; // Get full class name for classes that start with 'in-'
  switch (type) { 
    case 'in-left':
      // Transition in from left
    break;
    case 'in-bottom':
      // Transition in from bottom
    break;
  }
});

3 个答案:

答案 0 :(得分:4)

如果您知道可能的值,请使用hasClass

$('.slide').each( function(){
  var $this = $(this);
  if ($this.hasClass('in-left')) {

  } else if ($this.hasClass('in-bottom')) {

  } /* else if() ... */
});

答案 1 :(得分:2)

虽然我强烈建议您选择Toni's answer,但我想提供另一种解决问题的方法,甚至认为它不是您所要求的 - 尽管这样做因为你没有提供任何明确或解释,你想要的全部课程名称&#39;将返回

此方法采用带前缀的类名,然后使用prefix-name在每个元素上创建data-*属性;因此,前缀为"in-"的类用于生成带有类的后缀的data-in属性,在'-'字符成为属性值之后。所以:

<div class="in-left"></div>

变为:

<div class="in-left" data-in="left"></div>

这似乎是您所描述问题的合适解决方案,并允许您使用正常的&#39; /&#39;首选&#39;用于访问相关元素的语法;虽然在你的问题中有一些不确定性和缺乏清晰度的预期结果。

那就是说,一种方法如下:

// creating a simple jQuery plugin:
(function ($) {

    // the plugin-name:
    $.fn.fullClassFromPartial = function (opts) {

        // extending the 'defaults' with the
        // options supplied by the user:
        var s = $.extend({
            'partial': '',
            'join' : ''
        }, opts);

        // we proceed only if the user supplies a
        // value for the s.partial property:
        if (s.partial.length) {

            // returning the jQuery collection (this),
            // after iterating through that collection
            // using the each() method:
            return this.each(function (i, n) {

                // setting the data-* attribute equal
                // to the value of the s.partial value
                // after replacing non-alpha characters:
                n.dataset[s.partial.replace(/[^a-z]/g, '')] =

                   // setting the attribute-value, first
                   // using Function.prototype.call() to
                   // allow us to use Array.prototype.slice()
                   // on the Array-like return-value of
                   // the HTMLElement.classList property
                   // to convert the Array-like value into
                   // an Array:
                   Array.prototype.slice.call(n.classList, 0)

                       // using Array.prototype.filter()
                       // to retain only those elements
                       // upon whom the inner assessment
                       // returns a true/truthy value:
                       .filter(function (cN, i) {
                           // within the anonymous function the
                           // first argument ('cN') is the array
                           // element of the array over which
                           // we're iterating; the second argument
                           // ('i') is the index of that array-element
                           // in the Array.

                               // if the s.partial value is found at
                               // the beginning of the array-value,
                               // we retain this element in the array:
                               return cN.indexOf(s.partial) === 0;

                            // we convert into a map, using
                            // using Array.prototype.map()
                            // in order to create/return a new
                            // Array:
                            }).map(function (cN) {

                                // here we return the class-name
                                // after removing the s.partial
                                // prefix from it:
                                return cN.replace(s.partial, '');

                // should multiple attribute-values prefixed with
                // the same string exist, then we join them together
                // with the value supplied to the s.join property
                // which can be updated by the user via the 
                // supplied options:
                }).join(s.join);
            });

        // 
        } else {
            return this;
        }
    };

})(jQuery);

// calling the plugin (note that while I haven't restricted
// the selector to only those elements whose class contains
// the 'in-' string, that is definitely recommended (this is
// just a simple demo, though, and I want to show it working
// with a larger-than-necessary collection):
$('div').fullClassFromPartial({

    // setting the 'partial' property to the prefix
    // we're looking for:
    'partial': "in-",

    // setting the 'join' property to the string
    // with which we want to join multiple values
    // together:
    'join' : '_'
});

&#13;
&#13;
(function($) {
  $.fn.fullClassFromPartial = function(opts) {
    var s = $.extend({
      'partial': '',
      'join': ' '
    }, opts);

    if (s.partial.length) {
      return this.each(function(i, n) {
        n.dataset[s.partial.replace(/[^a-z]/g, '')] = Array.prototype.slice.call(n.classList, 0).filter(function(cN, i) {
          return cN.indexOf(s.partial) === 0;
        }).map(function(cN) {
          return cN.replace(s.partial, '');
        }).join(s.join || ' ');
      });
    } else {
      return this;
    }
  };

})(jQuery);

$('div[class*="in-"]').fullClassFromPartial({
  'partial': "in-",
  'join': '_'
});
&#13;
div {
  border: 2px solid #000;
  min-height: 2px;
  margin: 1em;
  padding: 0.5em;
}
[data-in]::before {
  content: attr(data-in);
}
[data-in=left] {
  border-left-color: #f90;
}
[data-in=right] {
  border-right-color: #f90;
}
[data-in=top] {
  border-top-color: #f90;
}
[data-in=bottom] {
  border-bottom-color: #f90;
}
[data-in=top_left] {
  background-color: #ffa;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="slide in-top"></div>
  <div></div>
  <div class="slide in-right"></div>
  <div class="left"></div>
  <div class="slide in-bottom"></div>
  <div class="in-bottom slide"></div>
  <div class="slide in-left"></div>
  <div class="slide in-top in-left"></div>
</div>
&#13;
&#13;
&#13;

外部JS Fiddle demo,用于实验和开发。

参考文献:

答案 2 :(得分:1)

你可以这样做:

var $els = $('.slide[class*="in-"]');
$.each( $els, function(k, v){

  var type ='';
    type = $(this).attr('class').split(' ')[1];
  if(type.indexOf('in-')==-1)
    type = $(this).attr('class').split(' ')[0];

  switch (type) { 
    case 'in-left':
      // Transition in from left
    break;
    case 'in-bottom':
      // Transition in from bottom
    break;
  }
});

这将解决您的问题。 Click here jsfiddle