Select2 渲染不正确

Select2 not rendering correctly

下面的代码无需在元素上调用 select2 即可完美运行。它添加了所有选项并按应有的方式呈现。

let selectInput = $('<select ' +
    'class="checklist-input" ' +
    'id="' + inputId + '" ' +
    'data-checklist-item-field="' + field + '" ' +
    'data-checklist-item-id="' + itemId + '" ' +
    (disabled ? 'disabled' : '') +
    '>');

$.each(data.summary_input_options, (_, val) => {
    selectInput.append(`<option value="${val.value}">${val.value}</option>`);
});

selectInput.val(value);

return selectInput;

然而,第二次我添加了对 jQuery 对象的 select2 调用,事情变得很奇怪,并且 select2 大部分时间都无法显示,如果它确实出现了——第二次我更改了 select 中的值,它又消失了。

selectInput.val(value).select2();

似乎 select2 被正确调用,但没有插入 HTML 来呈现 select,因为正如您在下面看到的,select2 是将它的辅助功能标签正确地插入到原来的 select:

<select class="checklist-input select2-hidden-accessible" id="checklist-summary-52" data-checklist-item-field="summary" data-checklist-item-id="52" data-select2-id="checklist-summary-52" tabindex="-1" aria-hidden="true">
    <option value="Yes" data-select2-id="29">Yes</option>
    <option value="No">No</option>
    <option value="Maybe">Maybe</option>
</select>

如果有人以前遇到过这个问题或有任何想法,请告诉我

您错过了 css class 即 select2。请补充。

You must append the html to DOM first then call the select2() function.

<select class="checklist-input select2 select2-hidden-accessible" id="checklist-summary-52" data-checklist-item-field="summary" data-checklist-item-id="52" data-select2-id="checklist-summary-52" tabindex="-1" aria-hidden="true">
   <option value="Yes" data-select2-id="29">Yes</option>
   <option value="No">No</option>
   <option value="Maybe">Maybe</option>
</select>

// try with this small change also (optional).
selectInput.val(value);
selectInput.select2();

Select2 期望 select 已经在 DOM 中。

您的代码(如提供的那样)没有(还)将它添加到 DOM,因此 select2 不知道在哪里添加它的元素。

您可以尝试将包装器添加到 selectInput 并为该包装器指定 dropdownParent,但它不太可能工作,因为 select2 将尝试在 DOM 进行更改。

解决方法: 先将 select 添加到 DOM,然后再将其更改为 select2。