jQuery - 有以类开头的类 [英] jQuery - has class that starts with
问题描述
什么是获得所有以输入
开头的类的div的最佳方法?换句话说, a
和 b
应该从以下内容返回,但不是 c
。
< div id =aclass =input1 foo>< / DIV>
< div id =bclass =foo input2>< / div>
< div id =cclass =xinput3 foo>< / div>
表面上的方式令人惊讶地被接受 here ,是 $(div [class ^ ='input']);
但当然错过 b
。当然 $(div [class * ='input']);
会在 c
。
我能想到的最好的就是这个怪物
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;
} );
}
有更清洁的方式吗?这是上面的工作小提琴
你可以在jQuery中创建自己的表达式
$。expr [':' ] .hasClassStartingWithInput = function(obj){
return(/\binput/).test(obj.className);
};
你可以用
$ b <$来检索这些div p $ p>
$( 'DIV:hasClassStartingWithInput');
一个JsFiddle示例: http://jsfiddle.net/7zFD6/
编辑:你也可以使用参数(没有在函数标识符内硬编码类名称)
$。expr [':']。 hasClassStartingWith = function(el,i,selector){
var re = new RegExp(\\b+ selector [3]);
return re.test(el.className);
}
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
You can create your own expression in jQuery
$.expr[':'].hasClassStartingWithInput = function(obj){
return (/\binput/).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/
这篇关于jQuery - 有以类开头的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!