您过于复杂了,只需使用addClass()匿名函数:
$('input').addClass(function () {
return this.value == '' ? 'empty' : '';
});
JS 小提琴演示。
显然,将empty类名更改为您希望拥有的任何类名;正如您可能已经猜到的那样,''以下:是一个空字符串,如果this.value不等于(之前的评估)将返回。''?
如评论中所述,如果能够在相关input元素变为非空时删除添加的类,那就更好了;考虑到这一点,一个简单的方法应该是显而易见的:
$('input:button').click(function () {
$('input').each(function () {
var that = $(this),
val = that.val();
if (val === '') {
that.addClass('empty');
} else {
that.removeClass('empty');
}
});
});
JS 小提琴演示。
其次,一种更简洁的方法,等效于上述方法:
$('input:button').click(function () {
$('input').each(function(){
$(this)[this.value == '' ? 'addClass' : 'removeClass']('empty');
});
});
JS 小提琴演示。
这利用了这样一个事实,即可以使用符号形式Object.propertyName和访问对象的方法Object['propertyName'],还可以使用在这些方括号中运行条件(三元)运算符来确定是否应该使用addClass()or方法来处理下面括号中提供的类名。removeClass()empty
参考: