jQuery,keyup事件未启动

jQuery, keyup event not firing

本文关键字:启动 事件 keyup jQuery      更新时间:2024-04-10

我在重构系统中的keyup事件时遇到问题,该事件最初看起来如下:

$('#quotation_search_client').on('keyup',function(){
    param=$('#quotation_search_client').val();
    if(param.length>=4){
        var params = {
            social_reason: $('#quotation_search_client').val()
        }
        var clients=ClientServices.getByFilter(params);
        var addresses=ClientServices.getAddresses(clients.clients);
        QuotationServices.fillClients(clients.clients, addresses);      
    }else{
        $('#customers_results').html("");
    }
});

当它是这样的时候,它工作得很好,但当我把它改成这个时:

$('#quotation_search_client').on('keyup',QuotationServices.searchClient({social_reason: $('#quotation_search_client').val()}));

并定义函数";searchClient";像这样:

    QuotationServices.searchClient = function(params){
        param=$('#quotation_search_client').val();
        if(param.length>=4){
            var clients=ClientServices.getByFilter(params);
            var addresses=ClientServices.getAddresses(clients.clients);
            QuotationServices.fillClients(clients.clients, addresses);      
        }else{
            $('#customers_results').html("");
        }
    };

它停止工作,当我打字时什么也没发生。控制台没有显示任何错误,所以我在searchClient 函数的开头写了一个console.log,很明显,当我的页面加载时,它会触发,显示params.social_reason带有一个空字符串,但当我键入一些内容时,正如我所说,什么都不会发生。我不知道我缺少了什么,我所做的只是将事件的代码复制/粘贴到searchClient函数中,并删除var params(因为我会将其作为参数接收),有什么帮助吗?

您在keyup事件声明之后立即执行函数,因此不会将函数传递给keyup事件。

你应该改为:

$('#quotation_search_client').on('keyup',QuotationServices.searchClient);

和变化:

QuotationServices.searchClient = function(){
    var params = {social_reason: $('#quotation_search_client').val()}
    var param = $('#quotation_search_client').val();
    if(param.length>=4){
        var clients=ClientServices.getByFilter(params);
        var addresses=ClientServices.getAddresses(clients.clients);
        QuotationServices.fillClients(clients.clients, addresses);      
    }else{
        $('#customers_results').html("");
    }
};