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

问题描述:

根据记录状态的具体值(“ACTIVE”与“INACTIVE”),我想给每个下拉结果记录一个特定的背景颜色。如何做?我尝试了以下:jquery自动完成 - 下拉结果的条件样式

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); 
       }); 
      };   

     }  
    }) 
... 

  • 你的功能甚至达到你的if(item.status...)所以这段代码不会求return年代以前。考虑将标记构建为字符串,然后在完成时返回html字符串。
  • 我会一类的activeinactive添加到<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'' 
}; 
+0

有道理。我将添加这些类......但是您能否更具体地了解第一点“考虑将标记构建为字符串,然后在完成时返回html字符串。并举例说明如何做到这一点? –

+0

我编辑了我的答案,其中包含一个示例 – sauntimo

+0

好主意。这工作,谢谢! –