jquery 自动完成 - 下拉结果的条件样式

jquery autocomplete - Conditional styling of dropdown result

根据记录状态的特定值("ACTIVE" 与 "INACTIVE"),我想为下拉结果的每条记录提供特定的背景色。怎么做?我尝试了以下方法:

json:

[{"id":"1234","label":"Player","status":"ACTIVE"},{"id":"1235","label":"Player","status":"ACTIVE"}, ...]

js:

...
autocomplete: ({
      source: function( request, response ) {
        ...
      },                        
      create: function() {

            $(this).data('ui-autocomplete')._renderItem  = function (ul, item) {
                return $( "<li>" )

                    if ( item.status == 'ACTIVE' ) { 
                        .append( "<a style='background-color: #eaffd6' href='/"+ item.id +"' >" + item.label + "</a>" )
                    }                   
                    if ( item.status == 'INACTIVE' ) {  
                        .append( "<a style='background-color: #ffe5e5' href='/"+ item.id +"' >" + item.label + "</a>" )
                    }   
                    //.append( "<a style='background-color: #ffe5e5' href='/"+ item.id +"' >" + item.label + "</a>" )
                    .appendTo( ul );
            };

            $(this).data('ui-autocomplete')._renderMenu = function( ul, items ) {
                var that = this;
                $.each( items, function( index, item ) {
                    that._renderItemData( ul, item );
                });
            };          

        }       
    })
... 
  • 你的函数 returns 在它到达你的 if( item.status...) 之前,所以这个代码永远不会被评估。考虑将标记构建为字符串,然后在完成后返回 html 的字符串。
  • 我会添加 activeinactive 的 class 到 <li> 元素,然后 css 规则 .active { background-color: #eaffd6; } .inactive { background-color: #ffe5e5 }

编辑 你可以试试

 $(this).data('ui-autocomplete')._renderItem  = function (ul, item) {
    var str_html = '<li class="' + item.status.toLowerCase() + '">'
        + '<a href="/"' + item.id + '" >' + item.label + '</a>'
        + '</li>'
    return str_html''
};