Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - jQuery - has class that starts with

What would be the best way to get all divs that have any class that starts with input? In other words, a and b should be returned from what's below, but not c.

<div id="a" class="input1 foo"></div>
<div id="b" class="foo input2"></div>
<div id="c" class="xinput3 foo"></div>

The ostensible way, which surprisingly was accepted here, is to do $("div[class^='input']"); but of course that misses b. And of course $("div[class*='input']"); will give a false positive on c.

The best I could come up with was this monstrosity

function getAllInputDivs() {
    return $("div").filter(function (i, currentDiv) {
        return $.grep($(currentDiv).attr("class").split(" "), function (val) {
            return val.substr(0, "input".length) === "input";
        }).length > 0;
    });
}

Is there a cleaner way? Here's a working fiddle of the above

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can create your own expression in jQuery

$.expr[':'].hasClassStartingWithInput = function(obj){
  return (/input/).test(obj.className);
};

and you can retrieve those div with

$('div:hasClassStartingWithInput');

a JsFiddle Example: http://jsfiddle.net/7zFD6/


Edit: you could also use a parameter (without hardcoding the class name inside the function identifier) in this way

$.expr[':'].hasClassStartingWith = function(el, i, selector) {
  var re = new RegExp("\b" + selector[3]);
  return re.test(el.className);
}

new example on http://jsfiddle.net/pMepk/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...