我正在尝试在页面加载时将select2框显示为其聚焦状态。 我已尝试以下内容:
$('#id').select2('focus');
$('#id').trigger('click');
$('#id').trigger('focus');
只有第一行似乎有任何效果,并且它确实聚焦了select2字段,但是它需要额外的按键才能显示搜索字段,并允许输入搜索字符串。
因此,如果您加载页面并开始输入:"搜索",则"S"将打开搜索框,然后剩余的键将输入其中,因此您将搜索"earch"。
我正在尝试在页面加载时将select2框显示为其聚焦状态。 我已尝试以下内容:
$('#id').select2('focus');
$('#id').trigger('click');
$('#id').trigger('focus');
只有第一行似乎有任何效果,并且它确实聚焦了select2字段,但是它需要额外的按键才能显示搜索字段,并允许输入搜索字符串。
因此,如果您加载页面并开始输入:"搜索",则"S"将打开搜索框,然后剩余的键将输入其中,因此您将搜索"earch"。
这在版本3.4.2中可以正常工作,不确定确切的实现时间。
$('#id').select2('focus');
如果你使用:
$('#id').select2('open');
可以直接输入搜索内容。
如果您使用:$('#id').select2('open').select2('close');
将焦点设置为创建的select2下拉列表。如果您在键盘上按下Enter
或Ctrl+向下箭头
,则可以打开它。
我个人认为这比以下写法更好:
$('#id').select2('focus');
因为你无法使用键盘打开select2下拉列表。
$('#id').select2('open').select2('close');
在使用select2 V4.0时,当其他方法无效时,此代码可使用并具有奖励作用。谢谢! - pdobb$(window).load(function(){
$('#id').prev('.select2-container').find('.select2-input').focus();
});
$('#s2id').select2('focus');
$('#s2id').select2('open');
$('document').ready(function(){
var opencustomer = $("#changedatachange").select2();
opencustomer.select2("open");
});
在Select2 4.0.2版本中,我遇到了一个问题,即使用select2('focus')时,列表看起来已经聚焦,但按下ENTER键后列表不会打开。
对于我来说,这是解决方案。
$('#id').select2();
$('.select2-selection', $('#id').next()).focus();
or
$('#id').next().find('.select2-selection').focus();
如https://forums.select2.org/t/search-being-unfocused/1203/10中所述,Select2 4.x和JQuery 3.6.0的组合目前存在焦点问题。
有两种解决方法:要么降级到JQuery 3.5.1,要么...
// hack to fix jquery 3.6 focus security patch that bugs auto search in select-2
$(document).on('select2:open', () => {
document.querySelector('.select2-search__field').focus();
});
var $field = $('select');
$field.select2();
var id = $field.attr('id');
var $spanLabel = $field.next().find("span[aria-labelledby='select2-" + id + "-container']");
$spanLabel.focus();
我尝试了其他两个答案,但运气不太好,可能是因为我通过json填充控件,在开始时它只是一个隐藏的输入,所以编程的open方法没有任何效果。
然而,以下方法对我来说完全没问题:
$(document).ready(function()
{
$('#s2id_autogen1').focus();
});
focus
选项不太直观:http://jsfiddle.net/mJEZK/13/ - Alvaro