打开后select2select所有元素

Select2 select all elements after opening

我有 select2,打开后需要 document.querySelectorAll select2 的所有项目。 我不能在打开之前 select 它们,因为在单击之前不会生成带有项目的容器。 我所有的 select2 项都有 class select2 项。 我试图通过使用 .on("select2:opening") 来处理这个问题,但是我的变量中没有数据。

$("#select").on("select2:opening", function(){
   selectAllItems();
});

function selectAllItems(){
    const items = document.querySelectorAll(".select2-item");

    console.log(items);
    console.log(JSON.stringify(items));
}

输出为

NodeList []
    length: 0

{}

Select2 的版本是 4.0.5。

尝试以下方法

$("#select").on("select2:opening", function(){
   let items = $('option:selected', this).val();
    selectAllItems(items);
});

function selectAllItems(items){
    
    console.log(items);
    console.log(JSON.stringify(items));
}

根据您想要所有 <li> 项的评论,您通常会在 selectAllItems() 函数中执行此操作,因为动态生成的列表包含在 <span> 元素中有 class .select2-container.

const items = $('.select2-container li');

但是,如果您在 select2:opening 事件上立即调用此函数,则列表还不会生成。您可以改为设置一个非常小的延迟,例如 100 毫秒 ,这将为生成列表提供足够的时间,然后您可以 select 中的项目。这应该适合你:

function selectAllItems() {
  const items = $('.select2-container li');
  console.log('items', items);
}

$(function() {
  $('#select').select2();
  
  $('#select').on('select2:opening', function (e) {
    setTimeout(selectAllItems, 100);
  });
});

我尝试使用没有超时的 select2:open 事件,但它产生了一个 <li> 用于加载结果,这是不正确的。不过,使用具有相同 100 毫秒超时的 select2:open 确实有效。

我要说的是,想要直接处理列表项是不寻常的 - select2 允许您处理原始 <select> 列表和 <option> 元素,并且是你应该努力与之互动的。上面的代码可以满足您的要求,但除非您有非常具体的原因,否则我不会单独处理这些 <li> DOM 元素。