jQuery自动完成:根据ID隐藏项目

时间:2015-09-28 08:47:53

标签: javascript jquery jquery-ui autocomplete jquery-ui-autocomplete

我有一个数组,其中一些对象具有相同的“id”属性,如下所示:

var regions = [
  {'id': 1, 'value': 'Ankara'},
  {'id': 2, 'value': 'İstanbul'},
  {'id': 2, 'value': 'Istanbul'}
]

如果有重复的话,我会尝试只显示某个ID的第一个对象(在这种情况下,我想显示'İstanbul'而不是'Istanbul')。 我试图在source属性中使用一个函数,但是我失败了,我不确定我需要在哪里做到这一点...这是一个片段:

var regions = [
	{'id': 1, 'value': 'Ankara'},
	{'id': 2, 'value': 'İstanbul'},
	{'id': 2, 'value': 'Istanbul'}
]

$('#myInput').autocomplete({
	source: regions
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<input type="text" placeholder="type here ..." id="myInput">

任何帮助都会受到赞赏。谢谢。

2 个答案:

答案 0 :(得分:0)

这可能是您的解决方案。我创建了一个函数,它将根据属性从数组中删除重复项。函数将向uniqueArray添加唯一对象,忽略具有相同id的所有下一个项目。

之后我将uniqueArray传递给jQuery自动完成。

请记住,Array.reduce适用于IE9 +

如果您有任何问题,请随时询问。

&#13;
&#13;
#define __NR_write 1
&#13;
var regions = [
	{'id': 1, 'value': 'Ankara'},
	{'id': 2, 'value': 'İstanbul'},
	{'id': 2, 'value': 'Istanbul'}
]

var uniqueRegions = removeDuplicates(regions, 'id')

function removeDuplicates(arr, field) {
    var u = [];
    arr.reduce(function (a, b) {
        if (a[field] !== b[field]) {
            u.push(b);
        }
        return b;
    }, []);
    return u;
}

$('#myInput').autocomplete({
	source: uniqueRegions
})
&#13;
&#13;
&#13;

答案 1 :(得分:0)

感谢评论中的vijayP,我设法实现了我尝试用_renderItem做的事情。

首先,你需要存储一个这样的变量:

var autoComplete = $('#myInput').autocomplete({});

然后你可以在其上使用_renderItem,这样你就可以自定义插件生成的列表:

autoComplete.autocomplete( "instance" )._renderItem = function( ul, item ) {
    //Do your stuff
}

现在,您可以在公开活动中完成所需的工作。

这是一个完整的代码段:

var regions = [{
  'id': 1,
  'value': 'Ankara'
}, {
  'id': 2,
  'value': 'İstanbul'
}, {
  'id': 2,
  'value': 'Istanbul'
}]

var autoComplete = $('#myInput').autocomplete({
  source: regions,
  open: function(event, ui) {
    var $ul = $('#regions');
    $ul.find('li').each(function(id, region) {
      var dataID = $(region).attr('data-id');
      var items = $ul.find('[data-id="' + dataID + '"]');
      console.log($(items).length);
      if ($(items).length > 1) {
        $(items).hide();
        $(items).first().show();
      }
    });
  },
  messages: {
    noResults: '',
    results: function() {}
  }
})
autoComplete.autocomplete("instance")._renderItem = function(ul, item) {
  var $ul = $(ul).prop('id', 'regions')
  return $('<li data-id="' + item.id + '">')
    .append(item.value)
    .appendTo($ul);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
<input type="text" placeholder="type here ..." id="myInput">

相关问题