正在获取DOM中的所有select2实例

Getting all select2 instance in DOM

本文关键字:select2 实例 获取 DOM      更新时间:2023-09-26

当select2是焦点时,我试图解除键的绑定,这似乎能在中工作

 $('#someId').on('select2-focus',function(){
    $(document).unbind('keypress');
});

但我想获得所有select2实例,我已经尝试过

 $('.select2').on('select2-focus',function(){
    $(document).unbind('keypress');
});

但它不起作用,我不想在我的页面中的每个select2中添加".custom_class"。有人能帮我做这个吗?提前谢谢。

如果有人仍然对原始问题的答案感兴趣,即"在DOM中获取所有select2实例":

// The $element can be a narrower scope, or the entire document.
$element = $(document);
$element.find('select').each(function (i, select) {
    var $select = $(select);
    // Make sure that the select has Select2.
    if($select.hasClass("select2-hidden-accessible")) {
         // Perform your action, e.g.:
         $select.on('select2-focus',function(){
             $(document).unbind('keypress');
         });
         // You can also use the console for debugging:
         // console.log($select);
    }
});

$select.hasClass("select2-hidden-accessible")检查取自原始文档:https://select2.org/programmatic-control/methods#checking-如果插件已初始化

但请注意,"select2焦点"事件可能不再存在,因为此处未列出:https://select2.org/programmatic-control/events。你应该能够使用$select.find('.select2-selection__rendered').on('focus', function ...),但我没有测试。

有关如何使用它的工作示例,请参阅我的jsfiddle中的Select2问题。注意function unobscurePlaceholdersOfSelect2()

jQuery('.select2-container').each(function(i,el){
    $(el).data('select2').close()
})

我不知道你的html是什么。但试试看?jQuery( "[attribute='value']" )

例如:$("input[type='text']")