2

我想在我的网站中实现一个搜索框,其中包含自动完成文本和照片。

这是我当前的代码:

HTML

<h4>search:<input type="text" id="name-list" /></h4>

JavaScript

$(function () {
    $("#name-list").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "/Home/Searchuser",
                type: "POST",
                dataType: "json",
                data: {
                    searchText: request.term,
                    maxResults: 10
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.DisplayName + " R:" + item.Reputation,
                            value: item.DisplayName,
                            id: item.Id
                        }
                    }))
                }
            })
        },
        select: function (event, ui) {
            alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id) : "Nothing selected, input was " + this.value);
        }
    });
});

我正在使用 ASP.NET MVC2,并且我将 json 字符串(在查询本地数据库之后)与图像 url 和其他信息从控制器传递到视图。文本工作正常。

谁能帮我如何渲染图像并附加到列表项?

4

1 回答 1

0

我对代码进行了这些更改,然后它运行良好。

CSS

DIV.list_item_container {
    height: 90px;
    padding: 0px;
}
DIV.image {
    width:90px;
    height: 90px;
    float: left;
}
DIV.description {
    font-style: italic;
    font-size: 1.1em;
    color: gray;
    padding: 5px;
    margin: 5px;
}
#name-list {
    width: 300px;
}

JavaScript

$(document).ready(function () {
    $('#name-list').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "/Home/Searchuser",
                data: {
                    searchText: request.term,
                    maxResults: 10
                },
                dataType: "json",
                success: function (data) {

                    response($.map(data, function (item) {
                        return {
                            value: item.DisplayName,
                            avatar: item.PicLocation,
                            rep: item.Reputation,
                            selectedId: item.UserUniqueid
                        };
                    }))
                }
            })
        },
        select: function (event, ui) {

            alert(ui.item ? ("You picked '" + ui.item.label) : "Nothing selected, input was " + this.value);

            return false;
        }
    }).data("autocomplete")._renderItem = function (ul, item) {
        var inner_html = '<a><div class="list_item_container"><div class="image"><img src="' + item.avatar + '"></div><div class="label"><h3> Reputation:  ' + item.rep + '</h3></div><div class="description">' + item.label + '</div></div></a><hr/>';
        return $("<li></li>")
            .data("item.autocomplete", item)
            .append(inner_html)
            .appendTo(ul);
    };
});
于 2012-10-04T11:56:50.480 回答