在jQuery中拆分项目

时间:2014-08-02 08:04:59

标签: javascript jquery jquery-ui autocomplete

Original Example

Failed Example

这里是返回的数据:

var availableTags = [
    'ActionScript|AppleScript|Asp',
    'BASIC',
    'Clojure|C++|C|COBOL|ColdFusion',
    'Erlang',
    'Fortran',
    'Groovy',
    'Haskell',
    'Java|JavaScript',
    'Lisp',
    'Perl|PHP|Python',
    'Ruby',
    'Scala|Scheme',
];

如何在renderItem函数中将项目拆分为数组,当用户键入PHP时,它只返回来自Perl | PHP | Python&#39的PHP?

这是我的代码:

$('#tags').autocomplete({
    source: availableTags,
    search: function(event, ui) {
        $('#wrapper').empty();
    },
})
.data('autocomplete')._renderItem = function(ul, item) {
    return $('<div class="element"></div>')
        .data('item.autocomplete', item)
    var smallchoice = item.label.split('|');                    
    $.each(smallchoice,function(j,smallchoice){
           $option = '<a href="#" >' + smallchoice+ '</a>'
         })

        .append($option)
        .appendTo($('#wrapper'));
};

1 个答案:

答案 0 :(得分:1)

以下是您尝试做的一个示例。

.data('autocomplete')._renderItem = function(ul, item) {
  var inp = $("#tags").val();
  var items = item.label.split("|");
  for (var i = 0; i < items.length; i++) {
      index = items[i].toUpperCase().indexOf(inp.toUpperCase());
      if (index == 0 || index > 0) {
          item = items[i];
          return $('<div class="element"></div>')
          .data('item.autocomplete', item)
          .append('<a href="#">' + item + '</a>')
          .appendTo($('#wrapper'));
      }
  }
};

JSFiddle

相关问题