Простая, простая реализация:
$.fn.some = function(callback) {
var result = false;
this.each(function(index, element) {
// if the callback returns `true` for one element
// the result is true and we can stop
if(callback.call(this, index, element)) {
result = true;
return false;
}
});
return result;
};
$.fn.every = function(callback) {
var result = true;
this.each(function(index, element) {
// if the callback returns `false` for one element
// the result is false and we can stop
if(!callback.call(this, index, element)) {
result = false;
return false;
}
});
return result;
};
В ES5 массивы уже предоставляют методы every
и some
, поэтомувы можете добиться того же с помощью встроенных методов:
okay = $("#myForm input").get().every(function(element) {
return $(element).val().length > 0
});
, но в более старой версии IE это не будет работать без HTML5 shim .