“Any” boolean function in jquery

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

    .is() with a function argument is what you're after.

    var anyEmpty = $('input.tb').is(function(index, element) {
        return !element.value;
    })
    

    WARNING:

    This function is surprising in that it doesn't short circuit. It will needlessly iterate through all selected elements, even if the callback has already been satisfied.

    let i = 0
    let result = $('div').is((index, element) => {
      i++;
      return element.tagName === 'DIV';
    })
    console.log(`count = ${i}, result = ${result}`);
    // count = 732, result = true
    

提交回复
热议问题