[英]Reduce multiple if else statements
My Name:<input class="clr" id="name" type="text" /><span class="clr" id="name_error">Name is required</span> <br /><br />
My Email Adress:<input class="clr" id="email" type="text" /><span class="clr" id="email_error">Email is required</span> <br /><br />
My Organisation Name:<input class="clr" id="organisation" type="text" /><span class="clr" id="org_error">Organisation is required</span> <br /><br />
I have 3 input fields. 我有3个输入字段。 I'm using
span
to display error message when submitting empty fields. 我在提交空字段时使用
span
来显示错误消息。
My problem is, if name
field is empty, we should get "Name is required"
error, if email
field is empty, we should get "email is required"
error and so on. 我的问题是,如果
name
字段为空,我们应该得到"Name is required"
错误,如果email
字段为空,我们应该收到"email is required"
错误等等。
For this, I'm writing below code. 为此,我写下代码。
if (name == "")
$("#name_error").show();
else
$("#name_error").hide();
if (email == "")
$("#email_error").show();
else
$("#email_error").hide();
if (organisation == "")
$("#org_error").show();
else
$("#org_error").hide();
Is there any way to reduce if/else statements? 有没有办法减少if / else语句?
$('input.clr').each(function(){
if ($(this).val() == "")
$(this).next('span.clr').show();
});
Before that, we need to hide them this way: 在此之前,我们需要以这种方式隐藏它们:
$('span.clr').hide();
You could do this : 你可以这样做:
var obj = window; // or something else, depending on your scope
['name', 'email', 'organisation'].forEach(function(v) {
var $e = $('#'+v+'_error');
if (obj[v]=="") $e.show();
else $e.hide();
});
Note that 注意
name
) would allow for a simpler code name
)将允许更简单的代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.