Check if all elements satisfy a condition

前端 未结 8 855
栀梦
栀梦 2020-12-10 11:05

I need a jQuery filter/map/each type function to check if ALL elements satisfy a condition:

function areAllValid(inputs){
     return $.someFunction(inputs,          


        
8条回答
  •  情深已故
    2020-12-10 11:18

    There are some minor optimization issues unaddressed by the existing answers, so I'll throw my hat in the ring with what I believe is the most readable/performant code.

    Add a jQuery extension method like this which will short circuit :

    /** 
    * Determines whether all elements of a sequence satisfy a condition.
    * @@param  {function} predicate - A function to test each element for a condition.
    * @@return {boolean}  true if every element of the source sequence passes the test in the specified predicate
    */
    $.fn.all = function (predicate) {
        $(this).each(function (i, el) {
            if (!predicate.call(this, i, el)) return false;
        });
        // we made it this far, we're good.
        return true;
    };
    

    Then call it like this:

    var allValid = $("form :input").all(function () {
                       return $(this).valid();
                    });
    

提交回复
热议问题