创建多个JavaScript变量?

时间:2017-04-20 20:39:05

标签: javascript

我是JavaScript新手。有人可以告诉我我做错了什么吗?我已经为HTML表单创建了一条错误消息。名称字段有效,但如果其他字段留空,我想创建单独的消息。

以下是我的JavaScript代码:

function MyComponent(props) {
  React.Component.prototype.apply(this, props);
  this.props = props;
  this.state = {
    clickCount: 0,
  };
}

2 个答案:

答案 0 :(得分:0)

  1. 句法: 未达到此代码:document.getElementById('erroremail').innerHTML = "Please enter your email";
  2. 在第一次返回之前放置它并删除第二次返回。

    if (name == "") {
    document.getElementById('error').innerHTML = "Please enter your name";
    document.getElementById('erroremail').innerHTML = "Please enter your email";
    return false;
    }
    
    1. 逻辑值:
    2. 为什么你会测试两次完全相同的东西?

      解决方案:

      测试空电子邮件=>做点什么

      测试空名=>做点什么

答案 1 :(得分:0)

代码中的问题是,在检查其他验证之前,您需要return。当你返回一些东西时,函数会停止,返回后没有任何内容被验证。

在您的情况下,您可以声明一个默认为var ret=true;的变量,如果某个条件不符合您的要求,则变为false。

例如:

function test() {
 var ret = true;
 if( 1 !== 1 ) {
  ret = false; //you will return false in the end
 }
 return ret; //return the result. from this point on, the function exits and doesn't do anything after
 alert("This will not be executed because there is a 'return' before");
}

上述函数将返回false并且它不会执行警报,因为您已经从该函数返回结果

您需要的是:

function validateForm() {
      var ret = true;
      var name = document.forms["contactform"]["name"].value;
      if (name == "") {
        document.getElementById('error').innerHTML = "Please enter your name";
        ret = false;
      }
      var email = document.forms["contactform"]["email"].value;
      if (email== "") {
       document.getElementById('erroremail').innerHTML = "Please enter your email";
        ret = false;
      }
      return ret;
    }