jQuery - 有以类开头的类

Ada*_*kis 12 javascript jquery

什么是获得所有以任何类开头的div的最佳方法input?换句话说,a并且b应该从什么下方,但不退还c.

<div id="a" class="input1 foo"></div>
<div id="b" class="foo input2"></div>
<div id="c" class="xinput3 foo"></div>
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,在这里接受的表面方式是做$("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;
    });
}
Run Code Online (Sandbox Code Playgroud)

有更干净的方式吗?这是上面的工作小提琴

fca*_*ran 22

您可以在jQuery中创建自己的表达式

$.expr[':'].hasClassStartingWithInput = function(obj){
  return (/\binput/).test(obj.className);
};
Run Code Online (Sandbox Code Playgroud)

你可以用它来检索那些div

$('div:hasClassStartingWithInput');
Run Code Online (Sandbox Code Playgroud)

一个JsFiddle示例:http://jsfiddle.net/7zFD6/


编辑:你也可以用这种方式使用一个参数(不用在函数标识符中硬编码类名)

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

http://jsfiddle.net/pMepk/1/上的新例子


小智 6

这是一种方式......

function getAllInputDivs() {
    return $("div").filter(function () {
        return /(?:^|\s)input/.test(this.className);
    });
}
Run Code Online (Sandbox Code Playgroud)

或者让它更通用......

function classStartsWith( tag, s ) {
    var re = new RegExp('(?:^|\\s)' + s);
    return $(tag || '*').filter(function () {
        return re.test(this.className);
    });
}
Run Code Online (Sandbox Code Playgroud)

或者indexOf如果你不喜欢正则表达式,请采用这种方法......

function classStartsWith( tag, s ) {
    return $(tag || '*').filter(function () {
        return this.className.indexOf(s)===0 || this.className.indexOf(' ' + s)>-1;
    });
}
Run Code Online (Sandbox Code Playgroud)

虽然您应该知道它不会测试制表符,只测试空格字符,因此如果使用制表符而不是空格,它可能会失败.


回到正则表达式版本,您可以通过将搜索到的字符串添加到选择器来提高效率.

然后它只测试div的子集.

function getAllInputDivs() {
    return $("div[class*='input']").filter(function () {
        return /(?:^|\s)input/.test(this.className);
    });
}
Run Code Online (Sandbox Code Playgroud)

随着.filter()应用到只有那些你知道有div的input某处类,性能会提高.

或者多功能版本看起来像这样:

function classStartsWith( tag, s ) {
    var re = new RegExp('(?:^|\\s)' + s);
    return $((tag || '*') + '[class*="' + s + '"]').filter(function () {
        return re.test(this.className);
    });
}
Run Code Online (Sandbox Code Playgroud)