...或some()
和every()
的正确名称是什么。基本上,我正在寻找一个函数或插件,可以让我写出类似的东西:
okay = $("#myForm input").every(function() {
return $(this).val().length > 0
})
或
hasErrors = $(listOfUsers).some(function() {
return this.errorCount > 0;
})
你明白了。
(在你曾经尝试过的小队到来之前,我用Google搜索并找到了jquery.arrayUtils,但该代码看起来并不令我信服。)
答案 0 :(得分:3)
简单,直接的实施:
$.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
});
但如果没有HTML5 shim,它将无法在较旧的IE版本中使用。
答案 1 :(得分:0)
你可以做这样的事情
okay = $("#myForm input").each(function() {
return $(this).val().length > 0
})
okay = $("#myForm input").find('class').each(function() {
return $(this).val().length > 0
})