为什么javascript中的nextSibling方法无法正常工作

时间:2014-09-11 17:17:44

标签: javascript html forms validation nextsibling

我有这个代码将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代码验证电子邮件和&amp;为相应的兄弟元素命名并输出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();
}

1 个答案:

答案 0 :(得分: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,因此您将错误设置为“Name必须大于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;