Select2性能适用于大量项目 [英] Select2 performance for large set of items

查看:238
本文介绍了Select2性能适用于大量项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将select2 jquery插件与Twitter引导程序一起使用.对于少量项目,它工作正常.但是,当列表很大(超过1500个项目)时,它的确会放慢速度.在IE中最慢.

I'm using select2 jquery plugin with twitter bootstrap. It's working fine for smaller number of items. But when the list is huge (more than 1500 items) it really slows down. It's slowest in IE.

常规"下拉列表可以非常快速地处理1500多个项目.有没有针对这种情况的解决方法?

Normal Dropdownlist works very fast with more than 1500 items. Are there any workarounds for this situation?

推荐答案

即使在IE8中,也可以通过对建议进行分页来使这项工作很好,

You can make this work good even in IE8 with paginating the suggestions,

代码:

// Function to shuffle the demo data
function shuffle(str) {
  return str
    .split('')
    .sort(function() {
      return 0.5 - Math.random();
  })
.join('');
}

// For demonstration purposes we first make
// a huge array of demo data (20 000 items)
// HEADS UP; for the _.map function i use underscore (actually lo-dash) here
function mockData() {
  return _.map(_.range(1, 20000), function(i) {
    return {
      id: i,
      text: shuffle('te ststr ing to shuffle') + ' ' + i,
    };
  });
}
(function() {
  // init select 2
  $('#test').select2({
    data: mockData(),
    placeholder: 'search',
    multiple: true,
    // query with pagination
    query: function(q) {
      var pageSize,
        results,
        that = this;
      pageSize = 20; // or whatever pagesize
      results = [];
      if (q.term && q.term !== '') {
        // HEADS UP; for the _.filter function i use underscore (actually lo-dash) here
        results = _.filter(that.data, function(e) {
          return e.text.toUpperCase().indexOf(q.term.toUpperCase()) >= 0;
        });
      } else if (q.term === '') {
        results = that.data;
      }
      q.callback({
        results: results.slice((q.page - 1) * pageSize, q.page * pageSize),
        more: results.length >= q.page * pageSize,
      });
    },
  });
})();

工作示例,其中包含20000个项目: http://embed.plnkr.co/db8SXs/preview

working example with 20000 items here: http://embed.plnkr.co/db8SXs/preview

plnkr embed不支持IE8,因此请尝试使用此链接在IE8上进行尝试: http://run.plnkr.co/plunks/db8SXs/

plnkr embed does not support IE8 so try it out on IE8 with this link instead: http://run.plnkr.co/plunks/db8SXs/

这篇关于Select2性能适用于大量项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆