将匿名函数传递给jquery selector expr [:]

时间:2012-08-13 23:29:42

标签: javascript jquery

在jQuery中,你可以运行一个选择器,其中每个元素都通过你定义的函数运行,就像这样(完全做作的例子):

jQuery.expr[':'].AllOrNothing= function(a,i,m){
    // a is the thing to match, m[3] is the input
    if(m[3] === "true"){
      return true;
    } else {
      return false;
    }
  };

然后你就可以使用它:

$("div:AllOrNothing(" + true + ")"); //returns all divs
$("div:AllOrNothing(" + false + ")"); //returns nothing

是否可以传递匿名函数而不是调用jQuery.expr[:].Name=

修改

我正在想象可以链接的东西如下:

$("div").filterByFunction(function(a,i,m){ ... })

2 个答案:

答案 0 :(得分:1)

听起来你只想使用内置的.filter()方法并传递一个自定义函数来检查兄弟元素,以决定是返回true还是false,然后隐藏其余元素。

$("section").filter(function() {
    // examine child div and return true or false
}).hide();

答案 1 :(得分:1)

为了完整起见,您可以通过添加filter

来自行实施$.fn
$.fn.customFilter = function(f) {
    var filtered = $();
    this.each(function() {
        if(f.call(this)) {
            filtered = filtered.add(this)
        }
    });
    return filtered;
}

$("div").filterByFunction(function(){ return $(this).text() != "test"; })

在这种情况下,不是你应该的。