获取 DOM 中所有 select2 实例

jay*_*emp 3 javascript jquery

我试图在 select2 成为焦点时解除按键绑定,这似乎有效

 $('#someId').on('select2-focus',function(){
    $(document).unbind('keypress');
});
Run Code Online (Sandbox Code Playgroud)

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

 $('.select2').on('select2-focus',function(){
    $(document).unbind('keypress');
});
Run Code Online (Sandbox Code Playgroud)

但它不起作用,我不想在页面中的每个 select2 中添加“.custom_class”。有人可以帮我解决这个问题吗?提前致谢。

小智 6

如果有人仍然对原始问题的答案感兴趣,即 \xe2\x80\x9eGetting all select2 instance in DOM\xe2\x80\x9c:

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

检查$select.hasClass("select2-hidden-accessible")取自原始文档:https://select2.org/programmatic-control/methods#checking-if-the-plugin-is-initialized

\n\n

但请注意,“select2-focus”事件可能不再存在,因为它未在此处列出:https: //select2.org/programmatic-control/events。您应该能够使用 \n $select.find(\'.select2-selection__rendered\').on(\'focus\', function ...),但我没有对此进行测试。

\n\n

有关如何使用此功能的工作示例,请参阅我的jsfiddle for a Select2 issues。注意function unobscurePlaceholdersOfSelect2().

\n