我使用以下函数执行验证:
//Validation
$('.sValidate').bind('blur', function() {
if (!$(this).val()) {
$(this).removeClass('short_input');
$(this).addClass('short_input_negative');
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
我的大多数输入类都是short_input.但其中一些也被命名long_input.
我怎么知道input触发了什么类blur,删除它并添加long_input_negative?
<input type="text" id="loginname" name="loginname" class="short_input sValidate" value="JDoe">
Run Code Online (Sandbox Code Playgroud)
您可以使用.hasClass()方法进行类检测:
$('.sValidate').bind('blur',function(){
if (!$(this).val()){
if( $(this).hasClass('long_input') ) {
$(this)
.removeClass('short_input');
.addClass('short_input_negative');
}
if( $(this).hasClass('short_input') ) {
$(this)
.removeClass('long_input');
.addClass('long_input_negative');
}
}
});
Run Code Online (Sandbox Code Playgroud)
来自jQuery doc .hasClass()
确定是否为给定的类分配了任何匹配的元素.
另一种方式是使用 .is()
$('.sValidate').bind('blur',function(){
if (!$(this).val()){
if( $(this).is('.long_input') ) {
// do something of long_input
}
if( $(this).is('.short_input') ) {
// do something of short_input
}
}
});
Run Code Online (Sandbox Code Playgroud)
来自jQuery doc .is()
根据选择器,元素或jQuery对象检查当前匹配的元素集,如果这些元素中至少有一个与给定的参数匹配,则返回true.