javascript - jquery autocomplete - 下拉结果的条件样式

标签 javascript jquery autocomplete jquery-ui-autocomplete

根据记录状态的特定值(“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 );
                });
            };          

        }       
    })
... 

最佳答案

  • 您的函数return甚至在它到达您的 if( item.status...) 之前所以这段代码永远不会被评估。考虑将标记构建为字符串,然后在完成后返回 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''
};

关于javascript - jquery autocomplete - 下拉结果的条件样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45220065/

相关文章:

javascript - CSS 选择器 : how to select elements with certain class name

javascript - 如何找到网页上隐藏文本的宽度?

jquery - Bootstrap 中的内容重叠

javascript - 大图(非常大的图)加载效果

java - 500,000 个街道名称——使用什么数据结构来实现快速搜索?

javascript - 在页面上显示当前月份

Javascript 内存管理泄漏

php - 如何切换具有 php 值的 div 内容

angularjs - 如何在 angularjs 自动完成 "iElement.autocomplete is not a function"中修复此错误

javascript - 当 $.removed 时自动完成不会 $.empty/comeback