我编写了一个 jquery 程序来验证 minlength,但它不起作用。
我不知道如何解决其中的“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>
最佳答案
变量的范围
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>
关于javascript - 调试minlength验证jquery程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41313549/