Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

javascript - jQuery selector to target any class name (of multiple present) starting with a prefix?

I'm considering one selection statement that would target one of many css class names in a single class attribute value based on a string prefix.

For example, I want any detail- prefixed class names to get targeted from the following sample links.

<a href="eg.html" class="detail-1 pinkify another">
<a href="eg.html" class="something detail-55 minded">
<a href="eg.html" class="swing narrow detail-Z">
<a href="eg.html" class="swing narrow detail-Z detail-88 detail-A">

It's reminiscent of how [class|="detail"] prefix selector works on a scalar attribute value, and also of .hasClass(className), but my question needs both concepts applied simultaneously.

Note: The detail- prefix won't necessarily be the first class name of the bunch.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because of the way the class attribute is designed, you'll need to make use of at least two other attribute selectors (notice the whitespace in [class*=" detail-"]):

$('a[class^="detail-"], a[class*=" detail-"]');

This selects <a> elements with a class attribute that

  • starts with detail-, or
  • contains a class prefixed with detail-. Class names are separated by whitespace per the HTML spec, hence the significant space character.

If you'd like to turn this into a custom selector expression, you can do this:

$.expr[':']['class-prefix'] = function(elem, index, match) {
    var prefix = match[3];

    if (!prefix)
        return true;

    var sel = '[class^="' + prefix + '"], [class*=" ' + prefix + '"]';
    return $(elem).is(sel);
};

Then select it like this:

$('a:class-prefix(detail-)');

Or if you'd like to place this in a plugin:

$.fn.filterClassPrefix = function(prefix) {
    if (!prefix)
        return this;

    var sel = '[class^="' + prefix + '"], [class*=" ' + prefix + '"]';
    return this.filter(sel);
};

Then call it like this:

$('a').filterClassPrefix('detail-');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...