jquery布尔迭代器
…或者some()
和every()
的正确名称是什么。 基本上,我正在寻找一个函数或插件,可以让我写下这样的东西:
okay = $("#myForm input").every(function() { return $(this).val().length > 0 })
要么
hasErrors = $(listOfUsers).some(function() { return this.errorCount > 0; })
你明白了。
(在你已经尝试过的小队到来之前,我用Google搜索并找到了jquery.arrayUtils ,但该代码看起来并不令我信服)。
一个简单,直接的实现:
$.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垫片 ,它将无法在旧的IE版本中使用 。
你可以做这样的事情
okay = $("#myForm input").each(function() { return $(this).val().length > 0 }) okay = $("#myForm input").find('class').each(function() { return $(this).val().length > 0 })