JQuery模糊验证问题 [英] JQuery Blur Validation Problem

查看:130
本文介绍了JQuery模糊验证问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表单,如果文本字段为空,我想使用blur进行验证。



下面的代码应该可以工作,但即使我弹出一些文本,请问,我做错了什么?

  var name = $(input#name).val (); 
$(input#name)。blur(function()
{
if(('input#name:empty'))
{
//测试
alert('Empty');
}
});


解决方案

要使用 $(this).val() ,如下所示:



$ $ $ $(input#name)。blur(function(){
if($(this).val() .length === 0){
//测试
alert('Empty');
}
});

目前您正在检查 if('input#name:empty') 这是真的,JavaScript中的任何字符串都是 true (这是弱类型的)。另外 :empty 选择器检查它没有子元素,而不是它的是空的,所以检查这个值是一个空字符串还是 .length code>是空的,就像我上面所说的那样:)

另外,除非这个ID存在于另一个不需要匹配的元素类型上, #name 就足够了,而且速度更快, input 前缀是多余的。


I have a simple form that I want to validate using blur if the text field is empty.

The below code should work, but keeps alerting me even if I pop in some text, please, what am I doing wrong?

var name = $("input#name").val();
$("input#name").blur(function() 
{
      if (('input#name:empty'))
      {
            // Testing
            alert('Empty');
      }
});

解决方案

You want to use $(this).val(), like this:

$("input#name").blur(function() {
   if ($(this).val().length === 0) {
     // Testing
     alert('Empty');
   }
});

Currently you're checking if('input#name:empty') which is true, any string is going to be true in JavaScript (which is weakly typed). Also the :empty selector checks that it has no child elements, not that its value is empty, so check that the value is an empty string, or the .length is empty like I have above :)

Also, unless there is the possibility of this ID being on another element type you don't want to match, #name will suffice and be faster, the input prefix is superfluous.

这篇关于JQuery模糊验证问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆