jQuery UI输入自动完成无匿名功能

jQuery UI input autocomplete without anonymous function

本文关键字:功能 UI 输入 jQuery      更新时间:2023-09-26

我设法让jQuery UI自动完成工作。然而,由于我在许多输入字段中使用它,我想使它更通用,所以我不必复制它。所以不用下面的代码:

$(function() {
    var cache = {};
    $("#searchGuyInput").autocomplete({
        minLength: 2,
        source: function(request, response) {
            // Getting a JSON array to populate the list
            var term = request.term;
            if (term in cache) {
                response(cache[ term ]);
                return;
            }
            $.getJSON("c_select_guy.php", {request: term}, function(data, status, xhr) {
                cache[ term ] = data;
                response(data);
            });
        },
        select: function(event, ui) {
            // What happens once I have selected a name from the list
            if (ui.item){
                createInputField(ui.item.Name + " " + ui.item.Surname,ui.item.guyID);
            }
        }
    })
    .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
        // Here I can format the JSON array to display the rows in the list
        return formatted;
    };
    function createInputField(message, guyID) {
        // creates a new div for the selected element
    };    
});

我尝试使用:

function autocomp(inputID) {  //CHANGED
    var cache = {};
    $(inputID).autocomplete({ //CHANGED
        minLength: 2,
        source: function(request, response) {
            // Getting a JSON array to populate the list
            var term = request.term;
            if (term in cache) {
                response(cache[ term ]);
                return;
            }
            $.getJSON("c_select_guy.php", {request: term}, function(data, status, xhr) {
                cache[ term ] = data;
                response(data);
            });
        },
        select: function(event, ui) {
            // What happens once I have selected a name from the list
            if (ui.item){
                createInputField(ui.item.Name + " " + ui.item.Surname,ui.item.guyID);
            }
        }
    })
    .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
        // Here I can format the JSON array to display the rows in the list
        return formatted;
    };
    function createInputField(message, guyID) {
        // creates a new div for the selected element
    };    
}
autocomp("#searchGuyInput"); //CHANGED

我用//CHANGED注释突出了这3个变化。

然而现在,即使自动完成返回给我一个很好的填充元素列表,当我从自动完成的select函数中的ui.item变量的元素选择是未定义的,它不再工作了!

我理解错了什么?

我认为$(function());只是在javascript中定义匿名函数的一种方式,因此,如果我将其命名,我可以多次调用它用于不同的输入字段。

找到这个线程的解决方案:如何创建通用的(可重用的)JavaScript自动完成函数

显然将其称为

autocomp("#searchGuyInput");

不起作用,你需要调用它为:

$(function() {
        autocomp("#searchGuyInput");
});

我仍然不明白这些$(function()调用做什么,所以如果有人想澄清它,我将非常高兴。