jQuery通过函数调用检查输入是否有值

jQuery checking if input has value by function call

本文关键字:是否 输入 检查 函数调用 jQuery      更新时间:2023-09-26

我定义了这个函数来检查输入字段是否为空

function hasValue() {
    if ( !!$.trim( $(this).val() ) ) 
        return true;
}

过滤jQuery Collection

$('#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 );
}); 

把这个传递给apply。并且不要在

之前执行()
hasValue.apply(this);

如果你想更好地使用你的函数,它必须接受一个元素作为参数,这不是一个很好的模式使用this像这样。首选在参数

中传递元素
function hasValue(elem) {
    return !!$.trim($(elem).val());
}

map的用法也一样:

$('#form').find( '.email' ).filter( hasValue );

And:

$('.input').change( function () {
    var empty = hasValue(elem); //throws an error
    $('#box').find('.required-tmp').toggleClass('required', empty );
}); 
$('.input').change( function () {
    var empty = hasValue.apply( $(this) ); //apply function should be used this way .
    // var empty = $(this).hasValue();       //doesn't work either
    $('#box').find('.required-tmp').toggleClass('required', empty );
}); 

为什么在hasValue方法中使用双否定?

其次,使用apply as:
var empty = hasValue.apply( this );

这将传递元素作为参数,你可以在那里使用!

第三,要检查值是否存在,您可以使用类型检查而不是trim,如:

if(typeof $(this).val !== 'undefined'){
return true;
}

看看这是否适合你!

apply语法应该类似于hasValue。apply($(this))代替hasValue()。Apply ($(this))

也许这会解决你的问题。

谢谢,问候,查理