jQuery自动完成隐藏的渲染结果

本文关键字:结果 隐藏 jQuery | 更新日期: 2023-09-27 18:05:53

我试图使用jQuery中的自动完成小部件,但是当我开始输入时,它下面没有显示任何内容。我知道它在做什么,因为当我输入时,我可以看到页面上的滚动条随着列表变短而变化,但我看不到结果。我的代码如下。任何帮助都是感激的。

我的控制器方法是这样的:

public ActionResult GetUsers(string query)
    {
        var empName = from u in HomeModel.CombineNames()
                      where u.StartsWith(query)
                      select u.Distinct().ToArray();
        return Json(empName);
    }

我的视图是这样的:

<script type="text/javascript">
$(document).ready(function() {
    $("input#autocomplete").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: '/Home/GetUsers',
                type: "POST",
                dataType: "json",

                data: { query: request.term },
                success: function(data) {
                    response($.map(data, function(item) {
                        return { label: item, value: item };
                    }));
                }
            });
        }
    });
})
</script>
<input  type="text" id = "autocomplete"/>

jQuery自动完成隐藏的渲染结果

您缺少一些东西,如渲染项,缓存管理。

代码应该看起来像这样:(假设您的操作返回一个字符串数组)

var cache = {},lastXhr;
            $( "input#autocomplete" ).autocomplete({
                minLength: 4,
                source: function (request, response) {
                    var term = request.term;
                    if (term in cache) {
                        response(cache[term]);
                        return;
                    }
                    var descripcion = new Array();
                    peticion = $.getJSON('/Home/GetUsers',{ query: request.term }, function (data, status, xhr) {
                        for (d in data) {
                            descripcion.push(data[d]);
                        }
                        cache[term] = descripcion;
                        if (xhr === peticion) {
                            response(descripcion);
                        }
                    });
                },
                select: function( event, ui ) {
                    $("input#autocomplete" ).val( ui.item);
                    return false;
                }
            })
            .data( "autocomplete" )._renderItem = function( ul, item ) {
                return $( "<li></li>" )
                    .data( "item.autocomplete", item )
                    .append( "<a>" + item +  " </a>" )
                    .appendTo( ul );
            };

尝试使用浏览器的检查工具来检查滚动条正在更改的区域。如果元素存在,您可能需要对CSS进行一些更改,以便文本颜色与背景颜色不同(或其他与显示相关的问题)。