Jquery Select2 plugin version check

▼魔方 西西 提交于 2019-12-10 03:45:36

问题


In my project I check if the Select2 plugin was loaded in this way

if (jQuery().select2)

But now I will try to verify what kind of version (3.5.X or 4.X) of Select2 plugin was loaded. I thought maybe you could check if there is an option/function introduced in version 4.X that is not present in the version 3.5.X. According to you, is it doable? How might I do it? Thank you


回答1:


There is a new isOpen method in Select2 4.0.

You can use something like this in your developer toolbar:

try {
    $("#a-select2-element").select2('isOpen');
    'select2 v4.x';
} catch(e) {
    'select2 v3.x';
} 

Tested with Select2 v3.5.3 and v4.0.3




回答2:


The events differ for Select2 v3 & v4! You could simply call the events of either version to run your code for only that version. If an event doesn't exist, it will be ignored. If you need to test within the change event, which v3 & v4 have in common, have a look at the code below:

var $el = $('#your-element'),
    s2Version3 = false,
    s2Version4 = false;

$el.on( 'select2:opening', function() {
    // this event only works for v4
    s2Version4 = true;
});

$el.on( 'select2-opening', function() {
    // this event only works for v3
    s2Version3 = true;
});

$el.on( 'change', function() {
    if ( s2Version3 ) {
        // change things for v3
    } else {
        // change things for v4
    }
});

P.S. To check if a jQuery function is available, isFunction comes in handy.

var s2Exists = $.isFunction( $.fn.select2 );


来源:https://stackoverflow.com/questions/35723573/jquery-select2-plugin-version-check

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!