在输入上添加类(如果值未更改,则删除)

我已经编写了这个简单的js来为焦点上的输入添加类,并在它失去焦点时删除它(如果值为空)。 但是,无论值是否为空,都不会删除该类。 感谢您的帮助,非常感谢

HTML:

JS:

 // When input is focussed $('#prospects_form > *').focus(function() { $(this).addClass("hasText"); }); $('#prospects_form > *').blur(function() { if ($(this).val === '') { $(this).removeClass("hasText"); } }); 

您也可以使用attrremoveAttr

 // When input is focussed $('#prospects_form > *').focus(function() { $(this).attr('class', 'hasText'); }); // blur event.. $('#prospects_form > *').blur(function() { if ($(this).val() == '') { $(this).removeAttr('class', 'hasText'); } }); 

错误是,你在模糊事件中缺少()前面的val 。 这是错误,并导致错误,你也会在控制台中看到它。

这也是一个小提琴:) http://jsfiddle.net/afzaal_ahmad_zeeshan/kdd84/1/

祝好运!

val是一个方法,这就是你必须调用它的原因(没有括号,将返回对函数的引用)

甚至不需要焦点事件! 将模糊处理程序转为:

 $('#prospects_form > *').blur(function(e) { var $t = $(this); $t[($t.val() === '' ? 'removeClass':'addClass')]('hasText'); }); 

感谢@ Novocaine88和@ Anthony-Grist的回答

$(this).val应该是$(this).val()this.value

JS(更新)

 // When input is focussed $('#prospects_form > *').focus(function() { $(this).addClass("hasText"); }); $('#prospects_form > *').blur(function() { if (this.value === '') { $(this).removeClass("hasText"); } });