This is post I am going to explain about break and continue in jQuery each function(loop).
jQuery’s functions like $.each( Object obj, Function fn ) or $().each() are not loops.These are iterative functions. $().each() is used to iterate jQuery object and you can use $.each( Object obj, Function fn ) to iterate over anything (for example, an array).
jQuery loops are not like javascript (for and while loop) loops. We can use ‘break;’ and ‘continue;’ inside a loop in javascript. But it will not work in jQuery loop ($().each()). 🙁
But there is way for it, if you need the same functionality for a jQuery loop.
We can use ‘return false;’ inside a jQuery loop to break it.
jQuery loops are functions. So when we use ‘return false;’ from a function, it will immediately stop execution of function. So, it will work llike ‘break;’.
Similarly if we use ‘return;’ (without passing true or false) it will work as ‘continue’;
Check with this below example
First normal javascript
function Demo()
{
for(var i=0;i<=10;i++)
{
if(i==2)
continue;
if(i==4)
break;
document.write(i+'<br/>’);
}
}
Output:
0
1
3
Now jQuery
function Demo()
{
$.each([0,1,2,3,4,5], function()
{
if(this == 2)
continue;
if(this == 4)
break;
document.write(this+'<br/>’);
});
}
Output:
0
1
3
It work same like below each function also
function Demo()
{
$(‘div’).each(function(index) {
if(index == 2)
continue;
if(index == 4)
break;
$(this).css(‘color’,’red’);
});
}
Hope this post helpful for you. if is there any better way then this please let me know.
Thanks,
Naga Harish.