简体   繁体   English

减少多个if else语句

[英]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语句?

Using jQuery effectively, you can do this way. 有效地使用jQuery,你可以这样做。

$('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 注意

  • this supposes a little more strictness, with the replacement of "org" by "organisation" 这假设更严格一些,用“组织”代替“组织”
  • I tried to mimic your code but changing at the root (ie where you fill the variables like name ) would allow for a simpler code 我试图模仿你的代码但是在根目录下改变(即你填充变量如name )将允许更简单的代码
  • if you know the DOM doesn't change and the error span always follows the input, Praveen's answer is probably simpler and suited 如果你知道DOM没有改变并且错误范围始终跟随输入,那么Praveen的答案可能更简单和适合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM