jQuery 在单个类名上使用“开始于”选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2178416/
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-08-26 12:57:00  来源:igfitidea点击:

Using 'starts with' selector on individual class names

jquery

提问by DA.

If I have the following:

如果我有以下几点:

<div class="apple-monkey"></div>
<div class="apple-horse"></div>
<div class="cow-apple-brick"></div>

I can use the following selector to find the first two DIVs:

我可以使用以下选择器来查找前两个 DIV:

$("div[class^='apple-']")

However, if I have this:

但是,如果我有这个:

<div class="some-other-class apple-monkey"></div>
<div class="apple-horse"></div>
<div class="cow-apple-brick"></div>

It will only find the second DIV, since the first div's class is returned as a string (I think) and doesn't actually start with 'apple-' but rather 'some-'

它只会找到第二个 DIV,因为第一个 div 的类作为字符串返回(我认为)并且实际上不是以“apple-”开头而是以“some-”开头

One way around that is to not use starts with, but instead contains:

一种解决方法是不使用开头,而是包含:

$("div[class*='apple-']")

The problem with that is it will also select the 3rd DIV in my example.

问题在于它还会在我的示例中选择第 3 个 DIV。

Question: Via jQuery, what is the proper way to use predicate selectors on individual class names, rather than the entire class attribute as a string? Is it just a matter of grabbing the CLASS, then splitting it into an array and then looping through each individual one with regex? Or is there a more elegant/less verbose solution?

问题:通过 jQuery,在单个类名上使用谓词选择器而不是将整个类属性作为字符串使用的正确方法是什么?是否只是获取 CLASS,然后将其拆分为一个数组,然后使用正则表达式遍历每个单独的数组?或者有更优雅/更简洁的解决方案吗?

回答by Josh Stodola

Classes that start with "apple-" plus classes that contain " apple-"

以“apple-”开头的类加上包含“apple-”的类

$("div[class^='apple-'],div[class*=' apple-']")

回答by Parrots

I'd recommend making "apple" its own class. You should avoid the starts-with/ends-with if you can because being able to select using div.applewould be a lot faster. That's the more elegant solution. Don't be afraid to split things out into separate classes if it makes the task simpler/faster.

我建议让“苹果”成为自己的课程。如果可以,您应该避免使用开始/结束,因为能够选择使用div.apple会快得多。这是更优雅的解决方案。如果它使任务更简单/更快,不要害怕将事情分成单独的类。

回答by Mexicoder

this is for prefix with

这是前缀

$("div[class^='apple-']")

$("div[class^='apple-']")

this is for starts with so you dont need to have the '-' char in there

这是为了开始,所以你不需要在那里有“-”字符

$("div[class|='apple']")

$("div[class|='apple']")

you can find a bunch of other cool variations of the jQuery selector here https://api.jquery.com/category/selectors/

你可以在这里找到一堆 jQuery 选择器的其他很酷的变体 https://api.jquery.com/category/selectors/

回答by equazcion

While the top answer here is a workaround for the asker's particular case, if you're looking for a solution to actually using 'starts with' on individual class names:

虽然这里的最佳答案是针对提问者的特殊情况的解决方法,但如果您正在寻找一种解决方案来实际在单个类名上使用“开头为”:

You can use this custom jQuery selector, which I call :acp()for "A Class Prefix." Code is at the bottom of this post.

您可以使用这个自定义 jQuery 选择器,我将其称为:acp()“A Class Prefix”。代码在这篇文章的底部。

var test = $('div:acp("starting_text")');

This will select any and all <div>elements that have at least one class name beginning with the given string ("starting_text" in this example), regardless of whether that class is at the beginning or elsewhere in the class attribute strings.

这将选择<div>具有至少一个以给定字符串开头的类名的任何和所有元素(在本例中为“starting_text”),无论该类是在类属性字符串的开头还是其他地方。

<div id="1" class="apple orange lemon" />
<div id="2" class="orange applelemon banana" />
<div id="3" class="orange lemon apple" />
<div id="4" class="lemon orangeapple" />
<div id="5" class="lemon orange" />

var startsWithapp = $('div:acp("app")');

This will return elements 1, 2, and 3, but not4 or 5.

这将返回元素 1、2 和 3,但不会返回4 或 5。

Here's the declaration for the :acpcustom selector, which you can put anywhere:

这是:acp自定义选择器的声明,您可以将其放在任何地方:

$(function(){
    $.expr[":"].acp = function(elem, index, m){
          var regString = '\b' + m[3];
          var reg = new RegExp(regString, "g");
          return elem.className.match(reg);
    }
});

I made this because I do a lot of GreaseMonkey hacking of websites on which I have no backend control, so I often need to find elements with class names that have dynamic suffixes. It's been very useful.

我这样做是因为我对没有后端控制的网站做了很多 GreaseMonkey 黑客攻击,所以我经常需要找到具有动态后缀的类名的元素。它非常有用。

回答by Gumbo

Try this:

尝试这个:

$("div[class]").filter(function() {
    var classNames = this.className.split(/\s+/);
    for (var i=0; i<classNames.length; ++i) {
        if (classNames[i].substr(0, 6) === "apple-") {
            return true;
        }
    }
    return false;
})

回答by code.rider

<div class="apple-monkey"></div>
<div class="apple-horse"></div>
<div class="cow-apple-brick"></div>

in this case as question Josh Stodola answer is correct Classes that start with "apple-" plus classes that contain " apple-"

在这种情况下,作为问题 Josh Stodola 的回答是正确的以“apple-”开头的类加上包含“apple-”的类

$("div[class^='apple-'],div[class*=' apple-']")

but if element have multiple classes like this

但是如果元素有多个这样的类

<div class="some-class apple-monkey"></div>
<div class="some-class apple-horse"></div>
<div class="some-class cow-apple-brick"></div>

then Josh Stodola's solution will do not work
for this have to do some thing like this

那么 Josh Stodola 的解决方案将不起作用,
因为必须做这样的事情

$('.some-parent-class div').filter(function () {
  return this.className.match(/\bapple-/);// this is for start with
  //return this.className.match(/apple-/g);// this is for contain selector
}).css("color","red");

may be it helps some one else thanks

可能对其他人有帮助,谢谢

回答by Ramón Mtz

If an element has multiples classes "[class^='apple-']" dosen't work, e.g.

如果一个元素有多个类“[class^='apple-']”不起作用,例如

<div class="fruits apple-monkey"></div>