“Any” boolean function in jquery

后端 未结 5 1201
再見小時候
再見小時候 2021-01-17 11:08

Is there any easy way to check if any elements in a jquery selector fulfill a condition? For instance, to check if any textboxes in a form are empty (kind o

5条回答
  •  孤城傲影
    2021-01-17 11:30

    I am adding this a year late for others who stumble across this:

    Malk's answer will fulfill the EXACT requirements in your example with:

    $('input.tb').filter(function() { return this.value.length == 0}).length != 0;
    

    A slightly more performant way of doing this (if the condition is met early, the filter function will still iterate over the remaining DOM elements) would be to write your own helper method (which, admittedly, the op has stated

    I know it could be done with a helper method, just curious if it was possible in one statement

    , but I came to this page hoping to save 2 mins writing my own):

    ;(function($) {
        //iterates over all DOM elements within jQuery object
        //and returns true if any value returned from the supplied function is 'truthy'.
        //if no truthy values are returned, returns false.
        //
        //Function( Integer index, Element element ) 
        $.fn.any = function(fn) {
           var i=0;
           for (;i

提交回复
热议问题