2

是否有可能在不对原始源代码产生很大影响的情况下扩展 jQuery.first()方法以便它可以接受谓词参数?从根本上说,我想要它做的是类似于 LINQ 的.First()C# 方法。在 JavaScript 中,它看起来像这样:

function first(arr, predicate) {
    for (var i = 0; i < arr.length; i++) {
        // return the first item fulfilling the predicate
        if (predicate.call(arr[i])) {
            return arr[i];
        }
    }
}

var myArray = [1, 3, 5],
    myPredicate = function() {
        return this >= 2;
    };

var result = first(myArray, myPredicate); // should give '3'

我知道它可以很容易地用 JavaScript 实现;我只是好奇是否可以在 jQuery 中轻松扩展现有方法。

使用的解决方案:

$.fn.firstOne = function(predicate) {
    // validate the predicate is a function
    if ($.isFunction(predicate)) {
        // iterate through each item, finding the first match
        for (var i = 0; i < this.length; i++) {
            if (predicate.call(this.eq(i), i)) {
                return this.eq(i);
            }
        }
    }

    // maintain chainability
    return $();
};
4

2 回答 2

3

您可以根据需要轻松(安全地)创建自己的方法,

$.fn.firstfn = function(fn) {
    return this.filter(fn).first()
}

$("#nav > li").firstfn(function() {
    return $(this).text() === "John Smith";
});

但是,我不建议您覆盖现有方法。只需添加您自己的方法。

于 2012-09-17T14:32:18.287 回答
1

您可以使用自己的函数轻松扩展 jQuery,请参阅此问题了解如何执行此操作

但它已经内置了first()与谓词/选择器有关的选择器。这里有些例子

$("#mycontainer li.classYouWant").first();
$("#mycontainer").find("another selector").first();
$("#mycontainer li a:first");
于 2012-09-17T14:26:44.217 回答