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
142 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 Reply

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/


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

...