在单个类名称上使用“开头为"选择器 [英] Using 'starts with' selector on individual class names

查看:101
本文介绍了在单个类名称上使用“开头为"选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我具有以下条件:

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

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

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

$("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>

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

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-'

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

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

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

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

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

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

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?

推荐答案

以"apple-"开头的类以及包含"apple-"的类

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

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

这篇关于在单个类名称上使用“开头为"选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆