我正在尝试根据函数参数中的定义构建几个动态if语句。如果提供了特定的键和值,我应该能够运行它们。我可以读取所有键和值,但不确定如何基于它们构建代码。这是作为函数参数传递的对象:
param = {
'fields': {
'email' : {
'match' : 'email'
},
'countAdults': {
'match' : 'number',
'range' : '1, 10'
}
}
};
这个位正在尝试解析对象
$.each(param.fields, function(key, value){ // reading definitions from the parameter
if(name == "'+key+'") $('[name="'+key+'"]').mandatory(); // define the begining of if
$.each(param.fields[key], function(subk, subv){
+= '.'+subk+'("'+subv+'")'; // adding more to the if statement
});
});
return (all if statement);
}
返回所有这些 if 语句后,我还想为默认情况运行一个 else 语句。我正在尝试将这些代码从主函数的主体移动到调用函数的位置,这样我就不必每次都自定义函数的主体。
我建议你改用元素,为你想要的每个验证添加一个类。喜欢这个:
<!doctype html>
<html>
<head>
<style type="text/css">
input.invalid { border: 1px solid red; }
</style>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
</script>
<script>
$(function()
{
$('.email').each(function()
{
var input = $(this);
input.keyup(function()
{
validate_as_email(input);
});
});
});
function validate_as_email(input)
{
var value = input.val();
if (is_email(value))
input.removeClass('invalid');
else
input.addClass('invalid');
}
function is_email(value)
{
return value.match
(/^[A-Z0-9._%-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i) != null;
}
</script>
</head>
<body>
Email:<br>
<input type="text" id="email" class="email">
</body>
</html>