javascript jQuery - 提取“以”前缀开头的类名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17367695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:02:58  来源:igfitidea点击:

jQuery - extract class name that 'starts with' prefix

javascriptjquery

提问by Atadj

My items have the following classes:

我的物品有以下几类:

<div class="class-x some-class-1 other-class"></div>
<div class="some-class-45 class-y"></div>
<div class="some-class-123 something-else"></div>

I'm wondering if there is an easy way to:

我想知道是否有一种简单的方法:

  1. Grab only all classes with some-class-prefix.
  2. Remove them from each element.
  3. Have their names (not corresponding DOM elements) in a variable?
  1. 只抓取所有带some-class-前缀的类。
  2. 从每个元素中删除它们。
  3. 将它们的名称(不是对应的 DOM 元素)放在一个变量中?

I can easily select such elements with jQuery( "div[class^='some-class-'], div[class*=' some-class-']" )but how its class name could be extracted with the shortest and the most readable code to a variable (can be some global object)?

我可以轻松地选择这样的元素,jQuery( "div[class^='some-class-'], div[class*=' some-class-']" )但是如何使用最短和最易读的代码将其类名提取到变量(可以是某个全局对象)?

回答by PSL

Like this?

像这样?

var arrClasses = [];
$("div[class*='some-class-']").removeClass(function () { // Select the element divs which has class that starts with some-class-
    var className = this.className.match(/some-class-\d+/); //get a match to match the pattern some-class-somenumber and extract that classname
    if (className) {
        arrClasses.push(className[0]); //if it is the one then push it to array
        return className[0]; //return it for removal
    }
});
console.log(arrClasses);

Fiddle

小提琴

.removeClass()accepts a callback function to do some operation and return the className to be removed, if nothing to be removed return nothing.

.removeClass()接受一个回调函数来执行一些操作并返回要删除的 className,如果没有要删除的内容则不返回任何内容。

回答by nderscore

You could loop through all the elements, pull the class name using a regular expression, and store them in an array:

您可以遍历所有元素,使用正则表达式提取类名,并将它们存储在数组中:

var classNames = [];
$('div[class*="some-class-"]').each(function(i, el){
    var name = (el.className.match(/(^|\s)(some\-class\-[^\s]*)/) || [,,''])[2];
    if(name){
        classNames.push(name);
        $(el).removeClass(name);
    }
});
console.log(classNames);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class-x some-class-1 other-class"></div>
<div class="some-class-45 class-y"></div>
<div class="some-class-123 something-else"></div>

回答by Ja?ck

You can iterate over each found node and iterate over the classes to find a match; if found, remove the class and log it:

您可以遍历每个找到的节点并遍历类以找到匹配项;如果找到,请删除该类并记录它:

var found = [];

$('div[class*="some-class-"]').each(function() {
  var classes = this.className.split(/\s+/),
  $this = $(this);

  $.each(classes, function(i, name) {
      if (name.indexOf('some-class-') === 0) {
          $this.removeClass(name);
          found.push(name);
      }
  });
});

Note that a selector like div[class*="some-class-"]is pretty expensive and since you need to perform extra processing anyway, it would be easier to just iterate over all divtags and process them:

请注意,像这样的选择器div[class*="some-class-"]非常昂贵,而且由于您无论如何都需要执行额外的处理,因此迭代所有div标签并处理它们会更容易:

var elements = document.getElementsByTagName('div'),
found = [];

$.each(elements, function(i, element) {
    var classes = element.className.split(/\s+/);

    $.each(classes, function(i, name) {
        if (name.indexOf('some-class-') === 0) {
            $(element).removeClass(name);
            found.push(name);
        }
    });
});

Modern browsers expose Element.classListwhich you can use to manipulate class names and Array.forEachfor iteration:

现代浏览器公开了Element.classList可用于操作类名和Array.forEach迭代的内容:

var found = [];

[].forEach.call(document.getElementsByTagName('div'), function(element) {
    (function(names, i) {
        while (i < names.length) {
            var name = names[i];
            if (name.indexOf('some-class-') === 0) {
                names.remove(name);
                found.push(name);
            } else {
                ++i;
            }
        }
    }(element.classList, 0));
});

回答by Damien

The easy way

简单的方法

You clould create your own filter :

您可以创建自己的过滤器:

$.fn.hasClassStartsWith = function(className) {
    return this.filter('[class^=\''+className+'\'], [class*=\''+className+'\']');
}

var divs = $('div').hasClassStartsWith("some-class-");
console.log(divs.get());

See fiddle

见小提琴