我定义了这个函数来检查输入字段是否为空
function hasValue() {
if ( !!$.trim( $(this).val() ) )
return true;
}
它非常适合过滤 jQuery 集合
$('#form').find( '.email' ).filter( hasValue );
但我也想重用 hasValue()
函数来切换类。
$('.input').change( function () {
var empty = hasValue().apply( $(this) ); //throws an error
// var empty = $(this).hasValue(); //doesn't work either
$('#box').find('.required-tmp').toggleClass('required', empty );
});
感谢任何帮助。
最佳答案
只需通过此即可申请。并且不要在之前执行 () :
hasValue.apply(this);
如果你想更好地使用你的函数,它必须接受一个元素作为参数,这样使用 this
不是一个好的模式。更喜欢在参数中传递元素
function hasValue(elem) {
return !!$.trim($(elem).val());
}
然后 map 的用法相同:
$('#form').find( '.email' ).filter( hasValue );
和:
$('.input').change( function () {
var empty = hasValue(elem); //throws an error
$('#box').find('.required-tmp').toggleClass('required', empty );
});
关于javascript - jQuery 通过函数调用检查输入是否有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39655970/