检查所有元素是否满足条件
我需要一个jQueryfilter/ map /每个类型函数来检查所有元素是否满足条件:
function areAllValid(inputs){ return $.someFunction(inputs, function(input) { return input.length > 0; }); }
如果ALL输入的长度> 0,则someFunction
应返回true。 在jQuery中有这样的东西吗?
答案是肯定的,它有一个方法grep,可以满足您的要求。 例如:
inputs= jQuery.grep(inputs, function(input){ return input.length>0; }); if(inputs.length>0) return true; return false;
我不测试它,也许它有一个小问题,但应该几乎像这样。
这将遍历每个项目,以及具有先前结果的条件,以便只有在所有项目的条件为真时才返回true。 您当然可以使用回调函数替换条件,并执行inputs.each(
而不是$('input')
但您可能需要稍微调整代码,具体取决于输入是否为jquery对象。
var all = true; $('input').each( function(index, value) { all = all & ($(value).val().length > 0); }); return all;
您不需要使用jQuery来执行此操作。 您可以使用在IE 9+中支持的Array.prototype.every在本机JavaScript中执行此操作。
function areAllValid(inputs){ return inputs.every(function(input) { return input.length > 0; }); }
如果您使用的是EcmaScript 2015,则可以进一步整理:
var areAllValid = inputs => inputs.every(input => input.length > 0);
不完全是,但创建一个很容易:
$.eachCondition = function (obj, conditionFunction){ var trueCount=0; var falseCount=0; $.each(obj, function (i,v) { if (conditionFunction.call(this,i,v)) { trueCount++; } else { falseCount++; } }); if (falseCount===0) { return true; } if (trueCount===0) { return false; } return undefined; }; $.fn.eachCondition = function (conditionFunction) { return $.eachCondition(this, conditionFunction); };
这是工作测试: http : //jsbin.com/iwanof/2/
我通常使用以下表单来获取JQuery中的匹配项
$.map($("[some selector]"), function(e) { return ([some matching mechanism]); }).indexOf(false) == -1;
在您的具体情况下,它看起来像这样:
$.map(inputs, function(e) { return (e.length > 0); }).indexOf(false) == -1;
现有的答案没有解决一些小的优化问题,所以我将把我的帽子放在环中,我认为这是最具可读性/性能的代码。
添加这样的jQuery扩展方法会短路:
/** * Determines whether all elements of a sequence satisfy a condition. * @@param {function} predicate - A function to test each element for a condition. * @@return {boolean} true if every element of the source sequence passes the test in the specified predicate */ $.fn.all = function (predicate) { $(this).each(function (i, el) { if (!predicate.call(this, i, el)) return false; }); // we made it this far, we're good. return true; };
然后这样称呼它:
var allValid = $("form :input").all(function () { return $(this).valid(); });
快速的小jQuery:
$(document).ready(function() { $('form input').keyUp(function() { var allValid = true; $.each($('form input'), function(input) { allValid = input.val().length > 0 } if ( allValid ) ... else ... }) });
function areAllValid(inputs){ return Array.prototype.every.call(inputs, function(input) { return input.length > 0; }); }