为什么 jQuery-select2 自动对焦不起作用以及如何修复它?

Kid*_*ida 14 jquery jquery-select2

我在所有项目中都使用 select2 并且工作正常。但在我的新项目中,我的 select2 输入没有按应有的方式聚焦。我必须点击它才能聚焦。问题是什么?我该如何解决它?

我不知道要显示哪部分代码,因为我没有更改标准 select2 函数中的任何内容。

Kid*_*ida 33

经过苦苦研究,我在GitHub页面上找到了原因和解决方案。

原因肯定是我在这个项目中使用了新版本的 jQuery 3.6(其他版本是基于 v3.4 构建的)。

解决方案(添加这段JavaScript代码就足够了):

      $(document).on('select2:open', () => {
        document.querySelector('.select2-search__field').focus();
      });
Run Code Online (Sandbox Code Playgroud)

  • 当使用多个带标签的多选时,此问题会中断(即 `$('.select2Tag').select2({tags: true,width: "100%",});`) (5认同)

Dum*_*san 13

为那些有多项选择的人更新了答案,这样您将专注于与选择字段关联的输入字段

$(document).on('select2:open', function(e) {
  document.querySelector(`[aria-controls="select2-${e.target.id}-results"]`).focus();
});
Run Code Online (Sandbox Code Playgroud)


小智 6

我想出了一个解决方案,它混合了 select2 github 页面(https://github.com/select2/select2/issues/5993)中发布的不同答案。

每个屏幕可使用多个 select2,也可与 multiple-select2 结合使用。

它只是从 OPEN 下拉列表 (.select2-container--open) 获取搜索输入,这就是我们的目标。

是的,这是一个肮脏的解决方法,但这是唯一对我有用的方法。

let forceFocusFn = function() {
  // Gets the search input of the opened select2
  var searchInput = document.querySelector('.select2-container--open .select2-search__field');
  // If exists
  if (searchInput)
    searchInput.focus(); // focus
};
    
// Every time a select2 is opened
$(document).on('select2:open', () => {
  // We use a timeout because when a select2 is already opened and you open a new one, it has to wait to find the appropiate
  setTimeout(() => forceFocusFn(), 200);
});
Run Code Online (Sandbox Code Playgroud)


Ama*_*rgi 5

以下解决方案对我来说适用于多个 select2。我编辑了Kida的解决方案:

$(document).on('select2:open', function(e) {
    window.setTimeout(function () {
        document.querySelector('input.select2-search__field').focus();
    }, 0);
});
Run Code Online (Sandbox Code Playgroud)