使用jQuery检查输入是否为空

问题描述:

我有一个表格,希望填写所有字段.如果单击某个字段然后又不填写,则我要显示红色背景.

I have a form that I would like all fields to be filled in. If a field is clicked into and then not filled out, I would like to display a red background.

这是我的代码:

$('#apply-form input').blur(function () {
  if ($('input:text').is(":empty")) {
    $(this).parents('p').addClass('warning');
  }
});

无论是否填写该字段,都将应用警告类.

It applies the warning class regardless of the field being filled in or not.

我在做什么错了?

$('#apply-form input').blur(function()
{
    if( !$(this).val() ) {
          $(this).parents('p').addClass('warning');
    }
});

并且您不一定需要.length或查看它是否为>0,因为无论如何,空字符串的求值为假,但出于可读性考虑:

And you don't necessarily need .length or see if it's >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:

$('#apply-form input').blur(function()
{
    if( $(this).val().length === 0 ) {
        $(this).parents('p').addClass('warning');
    }
});

如果您确定它将始终对textfield元素进行操作,则可以使用this.value.

If you're sure it will always operate on a textfield element then you can just use this.value.

$('#apply-form input').blur(function()
{
      if( !this.value ) {
            $(this).parents('p').addClass('warning');
      }
});

还应注意,如果只想引用一个单独的元素(假设上下文的后代/子对象中有一个文本字段),则$('input:text')会捕获多个元素,指定上下文或使用this关键字.

Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element (provided there's one textfield in the context's descendants/children).