【问题标题】:How to clone select2 v4 Ajax如何克隆 select2 v4 Ajax
【发布时间】:2015-12-01 14:53:01
【问题描述】:

我正在尝试使用 Select2 ver4 jquery 插件和使用加载 Select2 示例页面的远程数据进行 AJAX 调用 我正在尝试克隆一个包含 select2 工具的选择。 但是克隆时 select2 下拉菜单被禁用。

HTML 代码

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

jQuery 代码

     $.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();

【问题讨论】:

    标签: jquery ajax jquery-select2 jquery-select2-4


    【解决方案1】:

    创建克隆后,您必须为其运行完全相同的 select2 参数(除了您已销毁的原始参数)。您可以将参数声明为全局变量,然后在两个地方使用它(这是更好的做法),或者再次包含它们,为了优化答案,您可以在下面看到:

    $(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.
    
    });
    

    【讨论】:

    • 谢谢。我弄错了...我更正了班级的名称,但它不起作用
    • 您编辑的代码对我来说似乎工作得很好。您能否详细说明 “不起作用” 是什么意思,并可能创建一个 JSFiddle 来玩?
    • 真的吗?第一个选择元素没有问题,但重复的元素不起作用。此元素未连接到 json。这个元素总是显示“no Result”jsfiddle.net/uc1b74L3
    • 自最初的问题以来,您已经更改了整个代码。查看我新编辑的答案。
    • 太棒了!我希望您的代码是出色的工作。像魅力一样的运动!感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 2013-11-05
    • 1970-01-01
    • 2013-06-15
    • 2015-12-08
    • 2018-08-01
    相关资源
    最近更新 更多