illegal continue statement in javascript $.each loop
I am getting an error that this has an illegal continue statement.开发者_JAVA技巧 I have a list of words to check for form validation and the problem is it was matching some of the substrings to the reserved words so I created another array of clean words to match. If it matches a clean word continue else if it matches a reserved word alert the user
$.each(resword,function(){
$.each(cleanword,function(){
if ( resword == cleanword ){
continue;
}
else if ( filterName.toLowerCase().indexOf(this) != -1 ) {
console.log("bad word");
filterElem.css('border','2px solid red');
window.alert("You can not include '" + this + "' in your Filter Name");
fail = true;
}
});
});
The continue
statement is fine for normal JavaScript loops, but the jQuery each
method requires you to use the return
statement instead. Return anything that's not false and it will behave as a continue
. Return false, and it will behave as a break
:
$.each(cleanword,function(){
if ( resword == cleanword ){
return true;
}
else if ( filterName.toLowerCase().indexOf(this) != -1 ) {
//...your code...
}
});
For more information, see the jQuery docs.
Replace the continue with
return true;
You're using continue
which is meant for javascript for
loops inside a jquery each
handler. This won't work. The equivalent of continue
in jquery each
though is returning a non-false value.
if ( resword == cleanword ){
return true;
}
In jQuery.each loop you have to either return true or false to alter the loop interations:
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
So you would need to do this:
$.each(resword,function(){
$.each(cleanword,function(){
if ( resword == cleanword ){
return true;
}
else if ( filterName.toLowerCase().indexOf(this) != -1 ) {
console.log("bad word");
filterElem.css('border','2px solid red');
window.alert("You can not include '" + this + "' in your Filter Name");
fail = true;
}
});
});
in Jquery each method we are calling a function each time we loop inside array, so continue
will not work, we need to return true
to get out from a function.
only in simple loops without anonymous function we can use continue
You can't use continue there. It will continue automatically anyway, just remove that - and I think it should work per your description.
精彩评论