0

我有这段代码将 innerHTML 设置为输入类型 [email] 的兄弟元素,但不设置为输入类型 [name] 的兄弟元素。这是标记。

<div class="container">

<div>
  <input type="email" name="email" id="email" class="validate"/>
  <span class="email"></span>
</div>
<div>
  <input type="text" name="name" id="name" class="validate"/>
  <span class="name"></span>
</div>
<input type="submit" value="Download" id="install"/>  

</div>

这是标记部分。您会看到有同级元素跨度的输入。

以下是验证电子邮件和姓名的 javasript 代码,并将 errorText 输出到相应的兄弟元素(如果有)。

window.addEventListener("load",ready);

function _x(elem){
  return document.getElementById(elem) || document.getElementsByClassName(elem);
}

function ready(){

    function Start(){
        var call      = this;
        this.expEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;  
        this.button   = _x("install");
        this.field    = _x("validate");

        this.clicks    = function(){
            for(var i=0;i<this.field.length;i++){
            this.field[i].addEventListener("keyup",this.validate);
        }
    };

    this.validate = function(){
        call.check(this);
    }

    this.check    = function(field){
        var value = field.value,
            error = "",
            sibli = field.nextSibling; //This is giving problem
        switch(field.name){
            case "email":
                error = (!this.minLength(value,12)) ? "Email must be greater then 3 characters":"";
                error = (!this.maxLength(value,24)) ? "Email cannot be more then 24 characters":"";
                error = (!this.valEmail(value,12)) ? "The email format is invalid":"";   
            break;
            case "name":
                error = (!this.minLength(value,3)) ? "Name must be greater then 3 characters":"";
                error = (!this.maxLength(value,24)) ? "Name cannot be more then 24 characters":""; 
            break; 
        }
        sibli.innerHTML = error; //outputs only for input type [email]
    };

    this.minLength = function(field,length){
        return (field.length>length);
    };

    this.maxLength = function(field,length){
        return (field.length<length);
    };

    this.valEmail  = function(field){
        return (this.expEmail.test(field));  
    };
}

var start = new Start();
    start.clicks();
}
4

1 回答 1

1

看这部分:

  error = (!this.minLength(value,3)) ? "Name must be greater then 3 characters":"";
  error = (!this.maxLength(value,24)) ? "Name cannot be more then 24 characters":""; 

对于第一行,this.minLength 将返回 false,因为我们正在检查每个 keyup,因此您将错误设置为“名称必须大于 3 个字符”。然后在第二行中,this.maxLength 将返回 true,然后使用“!” 运算符导致 false 并且您的错误设置为 ""sibli.innerHTML = "";

所以基本上你想做:

    case "name":

        if (!this.minLength(value,3)) {
            error = "Name must be greater then 3 characters";
        } else if(!this.maxLength(value,24)) {
            error = "Name cannot be more then 24 characters";
        }

    break; 
于 2014-09-11T18:37:17.177 回答