【问题标题】:How can ajax based Select2 pre-population be formatted?如何格式化基于 ajax 的 Select2 预填充?
【发布时间】:2020-11-16 07:22:22
【问题描述】:

我们已经找到了几个为 Select2 预先填充选定选项的示例,但是我们都找不到处理格式化列表和选择选项的示例。我们在https://jsfiddle.net/gpsx62de/26/ 有一个 JS fiddle 来说明这个问题。在那个小提琴中,您可以在选择搜索中键入和 L 或其他内容,然后返回数据,格式化列表,如果您选择某些内容,则格式化选择。

但是,如果您单击该 JS Fiddle 中的按钮,该按钮旨在模拟每个 https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2 的预填充数据,则会返回数据(您可以取消注释 console.log 以查看它),但格式化的选择显示未定义预期值。有谁知道让预填充数据的格式化值正确显示的方法?

// Set up the Select2 control
$('#mySelect2').select2({
    ajax: {
        url: '/api/students'
    }
});

// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
    type: 'GET',
    url: '/api/students/s/' + studentId
}).then(function (data) {
    // create the option and append to Select2
    var option = new Option(data.full_name, data.id, true, true); //**** DOES IT MATTER WHAT IS PASSED HERE BECAUSE WE ARE NOT DISPLAY THE OPTION TEXT?? ***
    studentSelect.append(option).trigger('change');

    // manually trigger the `select2:select` event
    studentSelect.trigger({
        type: 'select2:select',
        params: {
            data: data //**** THIS DOES NOT SEEM TO SUPPORT FORMATTED SELECTIONS, SO HOW CAN THIS BE DONE? ***
        }
    });
});

【问题讨论】:

  • 您好,我检查了小提琴,您确定您使用的 URL 正确吗?看来来源真的不存在。
  • 它为我返回数据。你看到控制台日志输出了吗?

标签: javascript jquery ajax jquery-select2


【解决方案1】:

问题出在 format_selection 函数中。它接收的对象的格式取决于它是如何创建的。当您使用 new Option(text, value) 时,它只接收此 Option 对象的属性,而不是包含所有用户信息的原始对象。

一种解决方法是检查函数中的任一可能值:

function format_selection(obj) {
let name = obj.name || obj.element.text;
let email = obj.email || obj.element.email;
return $(`<div><b>${name}</b></div><div>(${email})</div>`);
}

为此,您应该在 Option 对象上附加 de 属性:

    var option = new Option(data.name, data.id, true, true);
    option.email = data.email;
    $('#sel').append(option).trigger('change');

【讨论】:

    【解决方案2】:

    https://jsfiddle.net/gpsx62de/26/ 的问题在于

    function format_selection(obj) {
      // Just add this to see the obj
      console.log(obj);
      return $(`<div><b>${obj.text}</b></div><div>(${obj.id})</div>`);
    }
    

    obj 对象只包含Option 类数据,所以:

    id: "1",
    selected: true,
    text: "Leanne Graham",
    title: ""
    

    所以你必须想办法将“data.email”传递给“format_selection”方法

    编辑

    这可能是一个解决方案

    $('#btn').on('click', function() {
      $.ajax({
        type: 'GET',
        url: 'https://jsonplaceholder.typicode.com/users/1'
      })
      .then(function(data) {
        console.log(data)
        // create the option and append to Select2
        $('#sel').append($('<option />')  // Create new <option> element
          .val(data.id)                   // Set value
          .text(data.name)                // Set textContent
          .prop('selected', true)
          .attr('data-name', data.name)   // Don't know why the .data(key, value) isn't working...
          .attr('data-email', data.email))
          .trigger('change');
      }); //then
    }); //click
    

    function format_selection(obj) {
      return $(`<div><b>${obj.element.dataset.name}</b></div><div>(${obj.element.dataset.email})</div>`);
    }
    

    这是小提琴https://jsfiddle.net/947jngtu/

    【讨论】:

    • 我试过你的小提琴,但似乎搜索不起作用,你知道吗?
    猜你喜欢
    • 2016-03-28
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 2016-06-03
    • 2016-12-04
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多