weixin_33720452 2015-09-05 16:09 采纳率: 0%
浏览 47

如何克隆select2 v4 Ajax

I am attempting to do an AJAX call with the Select2 ver4 jquery plugin and Using Loading remote data of Select2 sample page I am trying to clone a select which contains select2 tool. But select2 dropdown disabled when cloning.

HTML CODE

<tr>
<td>
<select class="js-example-data-ajax" id="sel1">
</select>
<button type="button" class="addline">Add Line</button>
</td>
</tr>

jQuery CODE

     $.fn.select2.amd.require(
    ["select2/core", "select2/utils", "select2/compat/matcher"],
    function (Select2, Utils, oldMatcher) {

  var $ajax = $(".js-example-data-ajax");

  function formatRepo (repo) {
    if (repo.loading) return repo.text;

    var markup = '<div class="clearfix">' +
    '<div class="col-sm-1">' +
    '<img src="' + repo.owner.avatar_url + '" style="max-width: 100%" />' +
    '</div>' +
    '<div clas="col-sm-10">' +
    '<div class="clearfix">' +
    '<div class="col-sm-6">' + repo.full_name + '</div>' +
    '<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + repo.forks_count + '</div>' +
    '<div class="col-sm-2"><i class="fa fa-star"></i> ' + repo.stargazers_count + '</div>' +
    '</div>';

    if (repo.description) {
      markup += '<div>' + repo.description + '</div>';
    }

    markup += '</div></div>';

    return markup;
  }

  function formatRepoSelection (repo) {
    return repo.full_name || repo.text;
  }

  $ajax.select2({
    ajax: {
      url: "https://api.github.com/search/repositories",
      dataType: 'json',
      delay: 250,
      data: function (params) {
        return {
          q: params.term // search term
        };
      },
      processResults: function (data, params) {
        // parse the results into the format expected by Select2
        // since we are using custom formatting functions we do not need to
        // alter the remote JSON data, except to indicate that infinite
        // scrolling can be used
        params.page = params.page || 1;

        return {
          results: data
        };
      },
      cache: true
    },
    escapeMarkup: function (markup) { return markup; },
    minimumInputLength: 1,
  });
});

$(document).on('click', '.addline', function () {
    var $tr = $(this).closest('tr');
    var $lastTr = $tr.closest('table').find('tr:last');

    $lastTr.find('.js-example-data-ajax').select2('destroy');

    var $clone = $lastTr.clone();

    $clone.find('td').each(function() {
        var el = $(this).find(':first-child');
        var id = el.attr('id') || null;
        if (id) {
            var i = id.substr(id.length - 1);
            var prefix = id.substr(0, (id.length - 1));
            el.attr('id', prefix + (+i + 1));
            el.attr('name', prefix + (+i + 1));
        }
    });
    $tr.closest('tbody').append($clone);
    $lastTr.find('.js-example-data-ajax').select2();
    $clone.find('.js-example-data-ajax').select2();
});
$('.js-example-data-ajax').select2();
  • 写回答

1条回答 默认 最新

  • weixin_33694620 2015-09-05 16:54
    关注

    After creating the clone, you have to run the very same select2 arguments for it (in addition to your original one that you've destroyed). You can either declare the arguments as a global variable and then use it in the two places (which is better practice), or to include them again, which for the sake of optimized answer you can see below:

    $(document).on('click', '.addline', function () {
        var $tr = $(this).closest('tr');
        var $lastTr = $tr.closest('table').find('tr:last');
    
        $lastTr.find('.js-example-data-ajax').select2('destroy');
    
        var $clone = $lastTr.clone();
    
        $clone.find('td').each(function() {
            var el = $(this).find(':first-child');
            var id = el.attr('id') || null;
            if (id) {
                var i = id.substr(id.length - 1);
                var prefix = id.substr(0, (id.length - 1));
                el.attr('id', prefix + (+i + 1));
                el.attr('name', prefix + (+i + 1));
            }
        });
        $tr.closest('tbody').append($clone);
    
        // ADDED:
        $(".js-example-data-ajax").select2({
          ajax: {
            url: "https://api.github.com/search/repositories",
            dataType: 'json',
            delay: 250,
            data: function (params) {
              return {
                q: params.term // search term
              };
            },
            processResults: function (data, params) {
              // parse the results into the format expected by Select2
              // since we are using custom formatting functions we do not need to
              // alter the remote JSON data, except to indicate that infinite
              // scrolling can be used
              params.page = params.page || 1;
    
              return {
                results: data
              };
            },
            cache: true
          },
          escapeMarkup: function (markup) { return markup; },
          minimumInputLength: 1,
        });
    
        // BAD PRACTICE: Make the entire { ajax: ...} block as a global variable,
        // then use it both here and on your original $ajax.select2(...) call.
    
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效