2017-02-01 14 views
0

#question_titleという入力があります。私はぼかしイベントでifステートメントを実行したい。長さをチェックしようとすると、定義されていません。 「これ」がここではうまくいかない理由は何ですか?上のそのようなプロパティ(length)がないようになぜ「this」は未定義ですか?

JS

$('#question_title').on('blur', function(){ 
    console.log('this.length = ' + this.length); 
    if (this.length > 1) { 
     // do something fabulous 
    } 
}); 

HTML

<div class="form-group question-title-wrap"> 
    <label for="question_title">What is your question?</label> 
    <input type="text" class="form-control" id="question_title"> 
</div> 
+3

$('#question_title').on('blur', function(){ console.log('this.value.length = ' + this.value.length); if (this.value.length > 1) { // do something fabulous } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-group question-title-wrap"> <label for="question_title">What is your question?</label> <input type="text" class="form-control" id="question_title"> </div>

、 'this'は' '要素ではなく、値のDOMノードを参照します。 'this.value.length'を試してみてください。 – Pointy

+2

'$(this).val()。length'はこれを行うjQueryの方法です。 – tadman

+0

それは:)答えとして追加してください。 Tx –

答えて

4

this要素自体ではなく、その値、従ってエラーundefinedを指し入力要素。

this.value.lengthを使用すると値と長さが得られます。その "ぼかし" ハンドラで

関連する問題