JQuery breaks out of the each loop

  • 2020-05-30 19:20:13
  • OfStack

1. jquery each loop, to achieve the functions of break and continue:

break -- return false;
continue -- use return ture;

2. How does jquery break out of the current each cycle

Some friends may think that continue and break can be used directly when jquery is out of the loop, but this does not work because jquery does not have these two commands.

Later, I searched the Internet and got the result:
return false; -- break out of all loops; Equivalent to the break effect in javascript.
return true; -- break out of the current cycle and enter the next cycle; Equivalent to the continue effect in javascript
case


$(function (){
 $("input[type='text']").each(function (i){ 
  var _val=$(this).val();
  alert(_val);
  if(_val=='2'){  
   return false; // Jump out of the loop
  }
 })
});

3. The Jquery each method breaks out of the loop and gets the return value

return false: will stop the loop (just as you would use 'break' in a normal loop).
return true: skip to the next loop (just as you would use 'continue' in a normal loop).


function test(){
var success = false;
$(..).each(function () {
   if (..) {
       success = true;
       return false;
   }
});
 return success ;
}

jquery is an object chain, so $(..) .each () returns a collection of objects. each(function(){}) : is a callback function in which the result cannot be returned outside the callback function each.


Related articles: