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 コードです。

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 を返すため、エラーを「名前は 3 文字より大きくする必要があります」に設定します。次に、2 行目で 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 に答える