“Any” boolean function in jquery

后端 未结 5 1359
再見小時候
再見小時候 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:45

    The problem with the current answers and also jQuery's own filtering functions, including .is(), .has(), and .filter() is that none of them short circuit as soon as the criteria is met. This may or may not be a large performance concern depending on how many elements you need to evaluate.

    Here's a simple extension method that iterates through a jQuery object and evaluates each element so we can early terminate as soon as we match the criteria.

    jQuery.fn.any = function(filter){ 
      for (i=0 ; i

    Then use it like this:

    var someEmpty= $(":input").any(function() { 
        return this.value == '';
    });
    

    This yields much better perf results:


    If you do go the pure jQuery route, $.is() is the same as !!$.filter().length so it probably makes for shorter and more imperative code to use is instead of filter.


    Here's an example of $.any() in action:

    jQuery.fn.any = function(filter){ 
      for (i=0 ; i
    
    
    
    
    

    Further Reading:

    • Jquery check form to see if any inputs has value
    • Is there an "exists" function for jQuery?
    • jQuery check if any text input has value

提交回复
热议问题