Heim > Fragen und Antworten > Hauptteil
wzCommon.checkRequired = function (parent, errorStr, fn) {
var required = parent.find('.required'),
oNumber = parent.find('.number'),
oTel = parent.find('.tel'),
flag = true;
if (required.length > 0) {
required.each(function () {
var getVal = $(this).val();
if (getVal === '') {
layer.msg(errorStr, {icon: 2});
flag = false;
return false;
}
});
}
if (oNumber.length > 0) {
oNumber.each(function () {
var verifyNumber = $(this).val();
if (isNaN(verifyNumber)) {
layer.msg(errorStr, {icon: 2});
flag = false;
return false;
}
});
}
if (oTel.length > 0) {
oTel.each(function () {
var getVal = $(this).val();
debugger;
if (!wzCommon.isPhoneNo(getVal)) {
layer.msg(errorStr, {icon: 2});
flag = false;
return false;
}
});
}
if (flag) {
fn();
}
return true;
};
wzCommon.checkStr = function (obj, errorStr, fn) {
if (obj.length > 0) {
obj.each(function () {
var getVal = $(this).val();
if (这里是不同条件) {
layer.msg(errorStr, {icon: 2});
flag = false;
return false;
}
});
}
if (flag) {
fn();
}
return true;
};
習慣沉默2017-05-19 10:17:57
// 既然你已经抽离出来, 只剩不同条件的判断, 那写一个检测器就好了啊.
var verifier = {
common : function(val) { return !!val },
required: function(val) { return val==='' },
number : function(val) { return isNaN(num) },
// ... 以此类推
};
// 这里你只需要处理一个 prop 参数, 这个参数你可以放到元素 data-prop 里, 也可以直接用类名, 很好处理
obj.each(function () {
var getVal = $(this).val();
// 假设你直接把 props 写在元素上
var prop = $(this).attr('data-prop') || 'common';
if ( verifier[prop](getVal) ){
layer.msg(errorStr, {icon: 2});
flag = false;
return false;
}
});
阿神2017-05-19 10:17:57
required = parent.find('.required'),
oNumber = parent.find('.number'),
oTel = parent.find('.tel')
这里做文章 再提取一个参数可以吗?
wzCommon.checkRequired = function (parent,el, errorStr, fn) {
var el= parent.find('.'+el),
flag = true;
if (el.length > 0) {
el.each(function () {
var getVal = $(this).val();
if (getVal === '') {
layer.msg(errorStr, {icon: 2});
flag = false;
return false;
}
});
}
if (flag) {
fn();
}
return true;
};