调试minlength验证jquery程序

时间:2016-12-24 13:08:24

标签: javascript jquery

我编写了一个用于验证minlength的jquery程序,但它无效。

我不知道如何在那里解决'select_this'问题。

我是jquery的初学者。

$(document).ready(function(){
	$('input[type="text"]').on('focus',function(){
		var select_this = $(this);
		minlength = select_this.attr('mLength');
		if(minlength != 0 && minlength > 0 && select_this.val().length < minlength ){
			select_this.after('<span>'+ minlength +' characters are required. </span>');
		}
	}).keyup(function(){
		if(select_this.val().length >= minlength ){
			select_this.next().remove();
		}
	}).blur(function(){
		select_this.next().remove();
	});
});
	    <p>
		    5<input type="text" mLength="5" />
		</p>
		<p>
		    10<input type="text" mLength="10" />
		</p>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

1 个答案:

答案 0 :(得分:2)

变量的范围

var select_this = $(this);
焦点事件处理程序内部的

仅在该处理函数内部可用,如果您需要在其他事件处理函数中访问它,那么也在那里声明它。

$(document).ready(function(){
	$('input[type="text"]').on('focus',function(){
		var select_this = $(this);
		minlength = select_this.attr('mLength');
		if(minlength != 0 && minlength > 0 && select_this.val().length < minlength ){
			select_this.after('<span>'+ minlength +' characters are required. </span>');
		}
	}).keyup(function(){
        var select_this = $(this);
		minlength = select_this.attr('mLength');
		if(select_this.val().length >= minlength ){
			select_this.next().remove();
		}
	}).blur(function(){
        var select_this = $(this);
		select_this.next().remove();
	});
});
<p>
		    5<input type="text" mLength="5" />
		</p>
		<p>
		    10<input type="text" mLength="10" />
		</p>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>